Sorting Algorithms and Custom Sorts
Understand bubble, selection, insertion, merge, quick and counting sort, and use built-in sorts with custom comparators to simplify problems.
Beginner · about 7 hours · difficulty 2/5
Learn first: Prefix Sums and Difference Arrays
Interviewers at service companies often ask you to write a sorting algorithm by hand. Product companies care more about whether you see that sorting first makes the problem easy.
The algorithms to know
- Bubble, selection, insertion: O(n^2). Insertion sort is fast on nearly sorted data and is stable.
- Merge sort: O(n log n) always, stable, O(n) extra space. Its merge step also counts inversions.
- Quick sort: O(n log n) average, O(n^2) worst case on bad pivots, in-place. Know Lomuto or Hoare partition.
- Heap sort: O(n log n), in-place, not stable.
- Counting and radix sort: O(n + k) when values lie in a small range.
Sorting as a tool
- Sort intervals by start, then merge (Merge Intervals, Meeting Rooms).
- Sort with a custom comparator: Largest Number compares a + b vs b + a.
- Sort then two pointers or binary search.
- Quickselect finds the kth smallest in O(n) average (Kth Largest Element in an Array).
Classic problems
Sort an Array (write merge sort), Merge Intervals, Insert Interval, Largest Number, Sort Colors, Kth Largest Element, Count Inversions, Maximum Gap.
Pitfalls
- Comparators that are not strict weak orderings (returning true for equal elements in C++) cause crashes or wrong output.
- Forgetting stability matters when sorting by one key after another.
You are ready to move on when you can write merge sort and quick sort from memory and explain when each is the better choice.
Key concepts
- Bubble, selection, insertion sort
- Merge sort and inversion count
- Quick sort and partitioning
- Heap sort
- Counting and radix sort
- Stability
- Custom comparators
- Quickselect
Mini project
Implement bubble, insertion, merge and quick sort in one file and time them on 1e3, 1e4 and 1e5 random and sorted inputs. Then solve: Merge Intervals, Insert Interval, Largest Number, Kth Largest Element in an Array, Count Inversions (GfG), and Meeting Rooms.
Check yourself
Why does quick sort degrade to O(n^2) on an already sorted array with a first-element pivot, and how do you avoid it?
Free resources
- VisuAlgo: sorting visualisations (VisuAlgo)
- Competitive Programmer's Handbook (Ch. 3) (CSES)
- GeeksforGeeks (GeeksforGeeks)