Sorting Algorithms Tutorial
See how sorting really works in Python: quadratic sorts, merge sort, quicksort, counting and radix sort, and Timsort
Intermediate4 lessonsabout 24 min of reading
This course is for developers who already write Python comfortably and want to understand sorting properly rather than memorise a table of complexities. It suits interview preparation, but it is aimed at the habit behind good answers: measure what an algorithm does, explain why, and know when not to write your own.
You will implement the simple quadratic sorts and count their comparisons to see why they are slow, build merge sort and quicksort and watch pivot choice decide between fast and catastrophic, learn why counting and radix sort can legitimately beat the O(n log n) barrier, and finish with what you will actually use in production: Python's stable sorted(), key functions and multi-key ordering.
The lessons run from simple to practical. First the quadratic sorts and why they cost what they cost, then the divide-and-conquer sorts, then the non-comparison sorts, then stability and Timsort. Every snippet is complete Python and its output was produced by running it, with counters instead of stopwatches so the numbers are repeatable. For background, see Data Structures and Arrays and Strings.
Sorting Algorithms lessons
- 1Sorting Algorithms: Insertion, Selection and Bubble Sort ComparedCompare insertion, selection and bubble sort in Python by counting comparisons and moves, and see exactly why they are quadratic.6 min read
- 2Merge Sort and Quicksort in Python: Pivot Choice and Worst CasesBuild merge sort and quicksort in Python, measure how pivot choice changes comparisons, and see why a bad pivot hits O(n^2) and recursion limits.6 min read
- 3Counting Sort and Radix Sort in Python: When O(n) Sorting Is LegitLearn counting sort and radix sort in Python, why they can beat O(n log n), and the limits on key range and width that decide when to use them.6 min read
- 4Python sorted() and Timsort: Stability and Multi-Key SortingUnderstand sort stability, how Python's Timsort behaves on real data, and how to sort by several keys with key functions, passes and cmp_to_key.6 min read
Preparing for an interview? Practise Data Structures & Algorithms interview questions
Learning Sorting Algorithms to land a job? Browse open roles or check which skills are trending.