11.11 Summary¶
1. Key takeaways¶
- Bubble sort sorts by swapping adjacent elements. Adding a flag to stop early improves its best-case time complexity to \(O(n)\).
- Insertion sort inserts one element from the unsorted section into its correct position in the sorted section each round. Although its time complexity is \(O(n^2)\), its low operation count makes it popular for small datasets.
- Quick sort sorts through partitioning. Repeatedly choosing the worst pivot can degrade its time complexity to \(O(n^2)\). Median or random pivot selection reduces this risk. Recursing on the shorter subarray reduces recursion depth and improves space complexity to \(O(\log n)\).
- Merge sort has division and merging phases, exemplifying divide and conquer. Sorting an array requires an auxiliary array and \(O(n)\) space, while sorting a linked list can be optimized to use \(O(1)\) space.
- Bucket sort has three steps: distribute data into buckets, sort within each bucket, and combine the results. It also uses divide and conquer and suits very large datasets. The key is distributing data evenly.
- Counting sort is a special case of bucket sort that sorts by counting occurrences. It suits large datasets with a limited value range and requires data that can be converted to positive integers.
- Radix sort sorts one digit at a time and requires data that can be represented as numbers with a fixed number of digits.
- Ideally, a sorting algorithm would be efficient, stable, in-place, and adaptive. As with other data structures and algorithms, however, no single sorting algorithm meets all these requirements. In practice, choose one according to the data's properties.
- Figure 11-19 compares common sorting algorithms in efficiency, stability, in-place operation, and adaptiveness.
Figure 11-19 Comparison of sorting algorithms
Description of Figure 11-19: Sorting algorithms compared
Compare the time complexity, space complexity, and four properties of nine common sorting algorithms. Their implementations and the characteristics of the data affect which one to use.
The legend at the bottom defines n as the input size. For bucket sort, k counts buckets. For counting sort, m is the range of values. For radix sort, k is the maximum number of digits and b is the radix. Thus k stands for different quantities in different rows.
The four properties on the right are stability (whether equal elements retain their relative order), in-place operation (whether elements can be rearranged without an auxiliary array comparable to the input in size; the recursion stack still counts toward space complexity), adaptivity (whether existing order can reduce the work), and comparison-based sorting (whether the algorithm compares elements or uses key distributions or digit counts).
Braces on the left group the nine algorithms into traversal-based, divide-and-conquer, and linear sorting. The main table lists best-, average-, and worst-case time complexity and worst-case space complexity, followed by stability, in-place operation, adaptivity, and use of comparisons.
Light green means “Good,” light blue “Fair,” and grayish purple “Poor.” The table gives these ratings in parentheses. Radix sort has O(nk) time in all three cases, yet the figure rates the best and average cases “Good” and the worst “Poor.” These are the figure’s ratings; performance in practice depends on the circumstances.
Bubble sort’s O(n) best-case time and its adaptivity assume it stops after a pass with no swaps. Quick sort’s O(log n) worst-case space assumes an optimized implementation that recurses only on the shorter subarray and handles the longer one in a loop. Ordinary recursion without this stack-depth optimization can use O(n) stack space in the worst case.
Bucket sort is stable if the sort within each bucket is stable. Its O(n+k) best and average times require the total cost of sorting all buckets to stay linear. For instance, a uniform distribution and a bucket count growing with n can keep the expected number of elements per bucket constant. Uniform distribution alone is insufficient with too few buckets. If all elements land in one bucket and its internal sort is quadratic, the worst-case time is O(n²).
The O(n+m) time for counting sort depends on the value range m. The O(nk) time for radix sort assumes a fixed radix b. With variable b, each counting-sort pass takes O(n+b), giving O(k(n+b)) over k passes. All three linear sorts impose requirements on data types and ranges. Their group label O(n) is conditional.
| Group | Complexity shown | Algorithms |
|---|---|---|
| Traversal-based sorting | O(n²) | Selection, bubble, insertion |
| Divide-and-conquer sorting | O(n log n) | Quick sort, merge sort, heap sort |
| Linear sorting | O(n) | Bucket, counting, radix |
| Algorithms | Best-case time | Average-case time | Worst-case time | Worst-case space | Stability | In-place operation | Adaptivity | Comparison-based? |
|---|---|---|---|---|---|---|---|---|
| Selection sort | O(n²) (Poor) | O(n²) (Poor) | O(n²) (Poor) | O(1) (Good) | Unstable (Poor) | In-place (Good) | Non-adaptive (Fair) | Comparison-based (Fair) |
| Bubble sort | O(n) (Good) | O(n²) (Poor) | O(n²) (Poor) | O(1) (Good) | Stable (Good) | In-place (Good) | Adaptive (Good) | Comparison-based (Fair) |
| Insertion sort | O(n) (Good) | O(n²) (Poor) | O(n²) (Poor) | O(1) (Good) | Stable (Good) | In-place (Good) | Adaptive (Good) | Comparison-based (Fair) |
| Quick sort | O(n log n) (Good) | O(n log n) (Good) | O(n²) (Poor) | O(log n) (Good) | Unstable (Poor) | In-place (Good) | Non-adaptive (Fair) | Comparison-based (Fair) |
| Merge sort | O(n log n) (Good) | O(n log n) (Good) | O(n log n) (Good) | O(n) (Poor) | Stable (Good) | Not in-place (Poor) | Non-adaptive (Fair) | Comparison-based (Fair) |
| Heap sort | O(n log n) (Good) | O(n log n) (Good) | O(n log n) (Good) | O(1) (Good) | Unstable (Poor) | In-place (Good) | Non-adaptive (Fair) | Comparison-based (Fair) |
| Bucket sort | O(n+k) (Good) | O(n+k) (Good) | O(n²) (Poor) | O(n+k) (Poor) | Stable (Good) | Not in-place (Poor) | Non-adaptive (Fair) | Non-comparison (Fair) |
| Counting sort | O(n+m) (Good) | O(n+m) (Good) | O(n+m) (Good) | O(n+m) (Poor) | Stable (Good) | Not in-place (Poor) | Non-adaptive (Fair) | Non-comparison (Fair) |
| Radix sort | O(nk) (Good) | O(nk) (Good) | O(nk) (Poor) | O(n+b) (Poor) | Stable (Good) | Not in-place (Poor) | Non-adaptive (Fair) | Non-comparison (Fair) |
Sorting algorithms involve trade-offs: none earns “Good” on every measure in the figure. Consider input size, existing order, range of values, available memory, and the need for stability.
2. Q & A¶
Q: When is stability necessary in a sorting algorithm?
We often sort objects by one of their attributes. For example, students have names and heights, and we want a multilevel sort. First sort by name to obtain (A, 180) (B, 185) (C, 170) (D, 170), then sort by height. An unstable algorithm may produce (D, 170) (C, 170) (A, 180) (B, 185).
Students D and C have switched positions, breaking the ordering by name. This is not what we want.
Q: Can the right-to-left and left-to-right scans in partitioning be reversed?
No. When the leftmost element is the pivot, the right-to-left scan must come first. This may seem counterintuitive, so let us examine why.
The final step of partition() swaps nums[left] and nums[i]. Afterward, every element to the left of the pivot must be <= the pivot, so nums[left] >= nums[i] must hold before that swap. If we scan left to right first and fail to find a larger element, the loop stops at i == j, where it is possible that nums[j] == nums[i] > nums[left]. The final swap would then move an element larger than the pivot to the far left, causing partitioning to fail.
For example, given [0, 0, 0, 0, 1], scanning left to right first produces [1, 0, 0, 0, 0] after partitioning, which is incorrect.
Conversely, if we choose nums[right] as the pivot, we must scan left to right first.
Q: In the recursion-depth optimization for quick sort, why does choosing the shorter subarray keep the depth at most \(\log n\)?
Recursion depth is the number of recursive calls that have not yet returned. Each partition divides the array into two subarrays. After the optimization, the subarray chosen for recursion is at most half the original length. Even in the worst case, where it is always exactly half, the depth is \(\log n\).
In the original quick sort, we may repeatedly recurse on the larger subarray, with lengths \(n\), \(n - 1\), \(\dots\), \(2\), and \(1\) in the worst case, giving depth \(n\). The optimization prevents this.
Q: If all array elements are equal, does quick sort take \(O(n^2)\) time? How can we handle this degeneration?
Yes. In this case, consider partitioning into three sections: elements smaller than, equal to, and greater than the pivot. Recurse only on the smaller and greater sections. If all elements are equal, a single partition then completes the sort.
Q: Why is bucket sort's worst-case time complexity \(O(n^2)\)?
In the worst case, all elements fall into one bucket. If an \(O(n^2)\) algorithm is used to sort that bucket, the overall time complexity is \(O(n^2)\).