Part 16 / Topic 6 of 12
Sorting, by hand and by library
Four classic sorts, by hand, then the one line you actually write in real code. Knowing the by-hand versions is what makes "Dual-Pivot Quicksort" and "TimSort" in the next paragraph mean something instead of being two more unfamiliar names.
| Sort | Big-O (time) | Space | Stable? | Idea |
|---|---|---|---|---|
| Bubble | O(n²), O(n) best case | O(1) | yes | repeatedly swap adjacent out-of-order pairs |
| Insertion | O(n²), O(n) best case | O(1) | yes | grow a sorted prefix one element at a time |
| Merge | O(n log n) always | O(n) | yes | split in half, sort each half, merge |
| Quick | O(n log n) average, O(n²) worst | O(log n) | no | pick a pivot, partition around it, recurse |
static void quickSort(int[] fares, int low, int high) {
if (low >= high) return;
int pivot = fares[high];
int boundary = low;
for (int i = low; i < high; i++) {
if (fares[i] < pivot) { swap(fares, i, boundary); boundary++; }
}
swap(fares, boundary, high);
quickSort(fares, low, boundary - 1);
quickSort(fares, boundary + 1, high);
}
$ javac SortingDemo.java
$ java SortingDemo
original: [820, 140, 560, 90, 310, 70, 450]
bubble sort: [70, 90, 140, 310, 450, 560, 820]
insertion sort:[70, 90, 140, 310, 450, 560, 820]
merge sort: [70, 90, 140, 310, 450, 560, 820]
quick sort: [70, 90, 140, 310, 450, 560, 820]
-- Arrays.sort: what you actually write in real code --
Arrays.sort: [70, 90, 140, 310, 450, 560, 820]
all four by-hand sorts match Arrays.sort: true
-- sorting objects: delivery riders by rating, highest first --
Asha - 4.8
Kiran - 4.5
Ravi - 4.2
-- Arrays.sort's actual algorithm, per the JDK docs --
primitives (int[], etc.): a Dual-Pivot Quicksort variant, not stable, in place
objects (Rider[], etc.): TimSort, a stable merge sort, O(n log n) worst case
stability matters for objects: equal-rated riders must keep their original order
Arrays.sort genuinely runs two different algorithms depending on what you hand it: primitives get an in-place Dual-Pivot Quicksort (fast, no stability needed because identical ints are indistinguishable anyway); objects get TimSort, a stable merge sort, because stability — equal elements keeping their original relative order — matters the moment the elements carry other data (two riders rated 4.5 should not swap places just because you re-sorted).
🔍 Going deeper:
Collections.sort(list)on aList<T>andlist.sort(comparator)both go through the same TimSort asArrays.sort(Object[])— there's no separate "collections sort algorithm" to learn.
Full program: examples/sorting/SortingDemo.java.
Done here? The practice set for Part 16 — including the solutions — is on the part page.