Sorting Algorithms
Understand how bubble, insertion, selection, merge, quick, heap and counting sort work, their complexities and stability, and when sorting simplifies a problem.
Beginner · about 7 hours · difficulty 3/5
Learn first: Recursion and Divide and Conquer
You will almost always call the library sort in real code, but interviews and university exams test whether you understand how sorting works and what guarantees each algorithm gives.
The algorithms
- Bubble, selection, insertion: O(n^2). Insertion sort is fast on nearly sorted data and small arrays.
- Merge sort: O(n log n) always, stable, needs O(n) extra memory. Great for linked lists and external sorting.
- Quick sort: O(n log n) average, O(n^2) worst case with bad pivots, in place. Random pivots make the worst case unlikely.
- Heap sort: O(n log n) worst case, in place, not stable.
- Counting / radix sort: O(n + k) for small integer ranges, not comparison-based.
Comparison sorts cannot beat O(n log n) in the worst case, which is a classic theory question.
Properties to remember
- Stable: equal elements keep their original order. Matters when sorting by multiple keys.
- In place: uses O(1) or O(log n) extra memory.
Sorting as a technique
Sorting first often unlocks simpler solutions: two pointers for pair sums, merging intervals, greedy scheduling, grouping duplicates. Custom comparators let you sort by any rule, like "largest number formed by concatenation".
Quickselect
Partitioning (from quick sort) finds the k-th smallest element in O(n) average without fully sorting.
Key concepts
- Bubble, selection, insertion sort
- Merge sort
- Quick sort and partitioning
- Heap sort
- Counting and radix sort
- Stability and in-place sorting
- Custom comparators
- Quickselect: k-th element in O(n) avg
Mini project
Implement merge sort, quick sort (random pivot) and counting sort and benchmark them, then solve: Sort an Array, Merge Intervals, Kth Largest Element (quickselect), Largest Number, Sort Colors, and Meeting Rooms.
Check yourself
Why is quick sort usually faster than merge sort in practice despite having a worse worst case?
Free resources
- VisuAlgo: Sorting (VisuAlgo)
- Sorting algorithms (GeeksforGeeks)
- MIT 6.006 Introduction to Algorithms (MIT OCW)