Sorting II (Merge, Quick, Bucket, Cyclic)
The sorting algorithms that actually scale: divide and conquer for O(n log n), counting tricks that beat it, and an in-place trick for arrays of 1 to n.
After this lesson you will be able to
- Explain why bubble, selection and insertion sort are too slow, and why merge and quick sort reach O(n log n).
- Write merge sort and trace a merge of two sorted halves.
- Write quicksort with a partition, and explain why a random pivot avoids the O(n²) worst case.
- Use counting sort and bucket sort when values are small integers or evenly spread.
- Use cyclic sort to find missing and duplicate numbers in an array of 1 to n, in O(n) time and O(1) space; use merge sort to count inversions.
Before you start. Sorting Basics (comparisons, stability, the simple sorts) and Recursion I (a function calling itself on smaller input).