diff --git a/README.md b/README.md index d3c4493..f4ca2a6 100644 --- a/README.md +++ b/README.md @@ -33,6 +33,7 @@ One module per article. This repository currently holds: | [`binary-search`](binary-search/) | Binary Search in Java: Iterative, Recursive, Lower/Upper Bound and 10 Interview Problems | this commit | | [`notification-service`](notification-service/) | System Design: Notification Service with Spring Boot and Kafka (Email, SMS, Push) | this commit | | [`linked-list`](linked-list/) | Linked List in Java: Singly, Doubly, Reverse, Cycle Detection and Interview Problems | this commit | +| [`quick-sort`](quick-sort/) | Quick Sort in Java: Lomuto vs Hoare Partition, Dry Run and Complexity | this commit | ## `collections` module diff --git a/quick-sort/README.md b/quick-sort/README.md new file mode 100644 index 0000000..2b08127 --- /dev/null +++ b/quick-sort/README.md @@ -0,0 +1,68 @@ +# quick-sort + +Companion code for the ankurm.com article **Quick Sort in Java: Lomuto vs Hoare Partition, Dry Run and Complexity** +(a full rewrite of three 2015 posts — "Implementing Quick Sort in Java" and the two "Implementing Quicksort Algorithm in Java" posts — now one article at the first URL). + +The Lomuto and Hoare partitions side by side, step-by-step dry runs, comparison/swap/depth counts for sorted, reverse, all-equal and few-distinct-key input, +random pivots, three-way partitioning, recursing into the smaller side, and the three 2015 programs run again: one corrupts arrays that contain duplicates, +one throws `ArrayIndexOutOfBoundsException`. Every figure and console line in the article is quoted from a file in `output/`, which the JUnit tests write +while asserting the same numbers. There is no `docs/` folder: the explanations live in the article itself. + +## Versions + +| Component | Version | Verified against | +|---|---|---| +| JDK | Temurin 25.0.5.1+2 (LTS) | `java -version` | +| JUnit | 6.1.3 | `junit-bom` `maven-metadata.xml` on Maven Central (latest GA) | +| Maven | 3.9.x | `mvn -version` | + +## Quickstart + +```bash +cd quick-sort +export JAVA_HOME=/path/to/jdk-25 PATH="$JAVA_HOME/bin:$PATH" +./scripts/run-all.sh # runs 16 tests and regenerates output/*.txt +java download/QuickSort.java # the single-file program from the article (type the numbers in) +``` + +The first Maven run must be online so the plugins land in the local cache. + +## Source layout + +``` +quick-sort/ +├── pom.xml +├── scripts/run-all.sh +├── download/QuickSort.java the single-file program, also attached to the article +├── src/main/java/com/ankurm/interviewlab/quicksort/ +│ ├── Lomuto.java last-element pivot, one scanning pointer +│ ├── Hoare.java middle-element pivot, two pointers walking inwards +│ ├── ThreeWay.java Dijkstra's < == > partition +│ ├── Randomized.java Lomuto with a random pivot +│ ├── StackSafe.java recurse into the smaller side, loop on the larger +│ ├── Measured.java instrumented copies that count comparisons, swaps and depth +│ ├── DryRuns.java instrumented copies that record every step +│ ├── Pitfalls.java two plausible-looking wrong Hoare variants +│ └── legacy/ the three 2015 programs, logic unchanged +├── src/test/java/.../ one test class per group of output files +└── output/*.txt captured real output +``` + +## Captured output (`output/`) + +| File | What it shows | +|---|---| +| `01-dry-run-lomuto.txt` | Lomuto on `[15, 34, 26, 67, 95, 24]`, every compare and swap | +| `02-dry-run-hoare.txt` | Hoare on the same array: 5 partition calls instead of 3 | +| `03-both-on-the-2015-samples.txt` | both schemes on the sample inputs of the other two 2015 posts | +| `04-legacy-temp-array.txt` | the 2015 temp-array version turning `[3, 1, 3, 2]` into `[1, 2, 3, 0]` | +| `05-legacy-first-pivot.txt` | the 2015 first-pivot version throwing on `[3, 1, 2]`; 4,680 of 10,000 random arrays | +| `06-worst-case.txt` | four schemes x five inputs, n = 5,000: comparisons, swaps, depth | +| `07-lomuto-vs-hoare-random.txt` | Hoare does fewer swaps but more comparisons on random input | +| `08-randomized-pivot.txt` | sorted input, 20 seeds: 67,134 to 85,451 comparisons instead of 12,497,500 | +| `09-three-way-duplicates.txt` | 20,000 keys from 10 distinct values, three schemes | +| `10-stack-depth.txt` | `StackOverflowError` on sorted input vs recursion depth 2 when recursing into the smaller side | +| `11-random-agreement.txt` | seven versions x 20,000 seeded arrays vs `Arrays.sort`, 0 disagreements | +| `12-pitfalls.txt` | two Hoare mistakes that look fine, reproduced | +| `13-jdk-source.txt` | what `Arrays.sort(int[])` and `sort(Object[])` call, read from `lib/src.zip` | +| `14-single-file-sessions.txt` | `java download/QuickSort.java` with the inputs of the 2015 posts | diff --git a/quick-sort/download/QuickSort.java b/quick-sort/download/QuickSort.java new file mode 100644 index 0000000..ee89af9 --- /dev/null +++ b/quick-sort/download/QuickSort.java @@ -0,0 +1,99 @@ +import java.util.Arrays; +import java.util.Random; +import java.util.Scanner; + +/** + * Quick Sort in Java, single file. Lomuto and Hoare partition side by side, plus a randomized pivot. + * + * javac QuickSort.java && java QuickSort + * (or, JDK 11+: java QuickSort.java) + * + * From ankurm.com: https://ankurm.com/implementing-quick-sort-in-java/ + */ +public class QuickSort { + + // ---- Lomuto: pivot = last element; i marks the end of the "<= pivot" zone ----------------- + static int lomutoPartition(int[] a, int lo, int hi) { + int pivot = a[hi]; + int i = lo - 1; + for (int j = lo; j < hi; j++) { + if (a[j] <= pivot) { + i++; + swap(a, i, j); + } + } + swap(a, i + 1, hi); + return i + 1; // the pivot's FINAL index + } + + static void lomutoSort(int[] a, int lo, int hi) { + if (lo < hi) { + int p = lomutoPartition(a, lo, hi); + lomutoSort(a, lo, p - 1); + lomutoSort(a, p + 1, hi); + } + } + + // ---- Hoare: pivot = middle element; two pointers walk towards each other ------------------- + static int hoarePartition(int[] a, int lo, int hi) { + int pivot = a[lo + (hi - lo) / 2]; + int i = lo - 1; + int j = hi + 1; + while (true) { + do { i++; } while (a[i] < pivot); + do { j--; } while (a[j] > pivot); + if (i >= j) { + return j; // a split point, NOT the pivot's final index + } + swap(a, i, j); + } + } + + static void hoareSort(int[] a, int lo, int hi) { + if (lo < hi) { + int p = hoarePartition(a, lo, hi); + hoareSort(a, lo, p); // p stays on the left side + hoareSort(a, p + 1, hi); + } + } + + // ---- Lomuto with a random pivot: no input is "the bad one" any more ------------------------- + static void randomizedSort(int[] a, int lo, int hi, Random rnd) { + if (lo < hi) { + swap(a, lo + rnd.nextInt(hi - lo + 1), hi); + int p = lomutoPartition(a, lo, hi); + randomizedSort(a, lo, p - 1, rnd); + randomizedSort(a, p + 1, hi, rnd); + } + } + + static void swap(int[] a, int i, int j) { + int t = a[i]; + a[i] = a[j]; + a[j] = t; + } + + public static void main(String[] args) { + Scanner in = new Scanner(System.in); + System.out.print("Enter the size of array: "); + int n = in.nextInt(); + int[] data = new int[n]; + System.out.println("Enter " + n + " elements (one per line):"); + for (int i = 0; i < n; i++) { + data[i] = in.nextInt(); + } + System.out.println("Before: " + Arrays.toString(data)); + + int[] a = data.clone(); + lomutoSort(a, 0, n - 1); + System.out.println("Lomuto: " + Arrays.toString(a)); + + a = data.clone(); + hoareSort(a, 0, n - 1); + System.out.println("Hoare: " + Arrays.toString(a)); + + a = data.clone(); + randomizedSort(a, 0, n - 1, new Random(42)); + System.out.println("Randomized: " + Arrays.toString(a)); + } +} diff --git a/quick-sort/output/01-dry-run-lomuto.txt b/quick-sort/output/01-dry-run-lomuto.txt new file mode 100644 index 0000000..cbcfccc --- /dev/null +++ b/quick-sort/output/01-dry-run-lomuto.txt @@ -0,0 +1,21 @@ +Lomuto partition, traced on [15, 34, 26, 67, 95, 24] +==================================================== + +partition [0..5] [15, 34, 26, 67, 95, 24], pivot = 24 (last) + j=0: 15 <= 24 -> i=0, swap a[0] and a[0] [15, 34, 26, 67, 95, 24] + j=1: 34 > 24 -> skip + j=2: 26 > 24 -> skip + j=3: 67 > 24 -> skip + j=4: 95 > 24 -> skip + place pivot: swap a[1] and a[5] [15, 24, 26, 67, 95, 34] -> pivot final at index 1 + partition [2..5] [26, 67, 95, 34], pivot = 34 (last) + j=2: 26 <= 34 -> i=2, swap a[2] and a[2] [15, 24, 26, 67, 95, 34] + j=3: 67 > 34 -> skip + j=4: 95 > 34 -> skip + place pivot: swap a[3] and a[5] [15, 24, 26, 34, 95, 67] -> pivot final at index 3 + partition [4..5] [95, 67], pivot = 67 (last) + j=4: 95 > 67 -> skip + place pivot: swap a[4] and a[5] [15, 24, 26, 34, 67, 95] -> pivot final at index 4 +final: [15, 24, 26, 34, 67, 95] + +partition calls: 3 diff --git a/quick-sort/output/02-dry-run-hoare.txt b/quick-sort/output/02-dry-run-hoare.txt new file mode 100644 index 0000000..53d3b35 --- /dev/null +++ b/quick-sort/output/02-dry-run-hoare.txt @@ -0,0 +1,19 @@ +Hoare partition, traced on [15, 34, 26, 67, 95, 24] +=================================================== + +partition [0..5] [15, 34, 26, 67, 95, 24], pivot = 26 (middle, index 2) + i stops at 1 (34), j stops at 5 (24) -> swap [15, 24, 26, 67, 95, 34] + i=2 j=2 pointers met/crossed -> split after index 2 + partition [0..2] [15, 24, 26], pivot = 24 (middle, index 1) + i=1 j=1 pointers met/crossed -> split after index 1 + partition [0..1] [15, 24], pivot = 15 (middle, index 0) + i=0 j=0 pointers met/crossed -> split after index 0 + partition [3..5] [67, 95, 34], pivot = 95 (middle, index 4) + i stops at 4 (95), j stops at 5 (34) -> swap [15, 24, 26, 67, 34, 95] + i=5 j=4 pointers met/crossed -> split after index 4 + partition [3..4] [67, 34], pivot = 67 (middle, index 3) + i stops at 3 (67), j stops at 4 (34) -> swap [15, 24, 26, 34, 67, 95] + i=4 j=3 pointers met/crossed -> split after index 3 +final: [15, 24, 26, 34, 67, 95] + +partition calls: 5 diff --git a/quick-sort/output/03-both-on-the-2015-samples.txt b/quick-sort/output/03-both-on-the-2015-samples.txt new file mode 100644 index 0000000..1260e8f --- /dev/null +++ b/quick-sort/output/03-both-on-the-2015-samples.txt @@ -0,0 +1,11 @@ +Both partitions on the sample inputs of the other two 2015 posts +================================================================ + +input: [15, 32, 45, 25, 34, 29, 14] +Lomuto: [14, 15, 25, 29, 32, 34, 45] (5 partition calls) +Hoare: [14, 15, 25, 29, 32, 34, 45] (6 partition calls) + +input: [15, 48, 66, 12, 48, 74, 12, 24, 56] +Lomuto: [12, 12, 15, 24, 48, 48, 56, 66, 74] (5 partition calls) +Hoare: [12, 12, 15, 24, 48, 48, 56, 66, 74] (8 partition calls) + diff --git a/quick-sort/output/04-legacy-temp-array.txt b/quick-sort/output/04-legacy-temp-array.txt new file mode 100644 index 0000000..23eb47e --- /dev/null +++ b/quick-sort/output/04-legacy-temp-array.txt @@ -0,0 +1,10 @@ +The 2015 temp-array version (post 2559): fine on distinct keys, corrupts duplicates +=================================================================================== + +distinct keys [15, 32, 45, 25, 34, 29, 14] -> [14, 15, 25, 29, 32, 34, 45] (correct) + +duplicates [3, 1, 3, 2] -> [1, 2, 3, 0] (expected [1, 2, 3, 3]) + the second 3 was never copied into temp[]; the leftover slot kept its initial 0. + +10,000 seeded random arrays (length 2..8, keys 1..9): 6,479 contained a duplicate; 6,479 came back wrong. +every wrong answer was an array with a duplicate; no array of distinct keys came back wrong. diff --git a/quick-sort/output/05-legacy-first-pivot.txt b/quick-sort/output/05-legacy-first-pivot.txt new file mode 100644 index 0000000..84ee3a6 --- /dev/null +++ b/quick-sort/output/05-legacy-first-pivot.txt @@ -0,0 +1,9 @@ +The 2015 first-pivot version (post 2530): the loop condition reads x[i] before checking i <= r +============================================================================================== + +the 2015 sample [15, 48, 66, 12, 48, 74, 12, 24, 56] -> [12, 12, 15, 24, 48, 48, 56, 66, 74] (correct) + +input [3, 1, 2]: ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3 +same input, operands of the && swapped: [1, 2, 3] + +10,000 seeded random arrays (length 1..8, keys 0..19): original threw on 4,680; fixed version wrong on 0. diff --git a/quick-sort/output/06-worst-case.txt b/quick-sort/output/06-worst-case.txt new file mode 100644 index 0000000..c6caeb0 --- /dev/null +++ b/quick-sort/output/06-worst-case.txt @@ -0,0 +1,31 @@ +Comparisons / swaps / deepest recursion, n = 5000 +================================================= + +n(n-1)/2 = 12,497,500 (what 'quadratic' means for this n) + +input scheme comparisons swaps depth +random LOMUTO_LAST 74,221 38,781 32 +random LOMUTO_RANDOM 72,503 32,022 27 +random HOARE_MIDDLE 86,170 14,464 27 +random THREE_WAY 114,975 46,953 26 + +already sorted LOMUTO_LAST 12,497,500 0 5,000 +already sorted LOMUTO_RANDOM 68,422 4,948 27 +already sorted HOARE_MIDDLE 66,807 0 14 +already sorted THREE_WAY 86,511 28,254 19 + +reverse sorted LOMUTO_LAST 12,497,500 2,500 5,000 +reverse sorted LOMUTO_RANDOM 71,483 31,556 28 +reverse sorted HOARE_MIDDLE 66,808 2,500 14 +reverse sorted THREE_WAY 86,142 28,030 19 + +all equal LOMUTO_LAST 12,497,500 0 5,000 +all equal LOMUTO_RANDOM 12,497,500 4,991 5,000 +all equal HOARE_MIDDLE 69,606 29,804 14 +all equal THREE_WAY 10,000 0 2 + +10 distinct keys LOMUTO_LAST 1,266,199 7,876 545 +10 distinct keys LOMUTO_RANDOM 1,266,490 14,752 542 +10 distinct keys HOARE_MIDDLE 77,651 25,334 21 +10 distinct keys THREE_WAY 35,969 14,705 7 + diff --git a/quick-sort/output/07-lomuto-vs-hoare-random.txt b/quick-sort/output/07-lomuto-vs-hoare-random.txt new file mode 100644 index 0000000..9af4819 --- /dev/null +++ b/quick-sort/output/07-lomuto-vs-hoare-random.txt @@ -0,0 +1,16 @@ +Lomuto vs Hoare on random distinct-ish keys (seed 7) +==================================================== + +n scheme comparisons swaps +1,000 LOMUTO_LAST 10,128 4,547 +1,000 HOARE_MIDDLE 15,679 2,301 + Hoare used 0.51x the swaps of Lomuto + +10,000 LOMUTO_LAST 155,168 66,283 +10,000 HOARE_MIDDLE 193,958 30,750 + Hoare used 0.46x the swaps of Lomuto + +100,000 LOMUTO_LAST 2,050,086 1,016,714 +100,000 HOARE_MIDDLE 2,377,190 387,156 + Hoare used 0.38x the swaps of Lomuto + diff --git a/quick-sort/output/08-randomized-pivot.txt b/quick-sort/output/08-randomized-pivot.txt new file mode 100644 index 0000000..c6f17bf --- /dev/null +++ b/quick-sort/output/08-randomized-pivot.txt @@ -0,0 +1,28 @@ +Random pivot on already-sorted input, n = 5000, seeds 1..20 +=========================================================== + +Lomuto, last element as pivot: 12,497,500 comparisons + +seed 1: 72,954 comparisons, depth 29 +seed 2: 70,214 comparisons, depth 26 +seed 3: 67,134 comparisons, depth 29 +seed 4: 67,613 comparisons, depth 25 +seed 5: 85,451 comparisons, depth 34 +seed 6: 73,353 comparisons, depth 29 +seed 7: 68,648 comparisons, depth 29 +seed 8: 67,756 comparisons, depth 26 +seed 9: 71,645 comparisons, depth 29 +seed 10: 69,475 comparisons, depth 25 +seed 11: 70,826 comparisons, depth 27 +seed 12: 70,267 comparisons, depth 27 +seed 13: 73,057 comparisons, depth 31 +seed 14: 72,339 comparisons, depth 31 +seed 15: 71,259 comparisons, depth 27 +seed 16: 71,299 comparisons, depth 28 +seed 17: 71,051 comparisons, depth 29 +seed 18: 73,109 comparisons, depth 28 +seed 19: 71,353 comparisons, depth 29 +seed 20: 72,255 comparisons, depth 27 + +over 20 seeds: min 67,134, max 85,451 comparisons, deepest recursion 34 +n * log2(n) = 61,439 diff --git a/quick-sort/output/09-three-way-duplicates.txt b/quick-sort/output/09-three-way-duplicates.txt new file mode 100644 index 0000000..cd0b045 --- /dev/null +++ b/quick-sort/output/09-three-way-duplicates.txt @@ -0,0 +1,7 @@ +20,000 keys drawn from only 10 distinct values +============================================== + +scheme comparisons swaps depth +LOMUTO_LAST 20,089,334 26,134 2,082 +HOARE_MIDDLE 338,316 121,964 23 +THREE_WAY 102,334 44,128 6 diff --git a/quick-sort/output/10-stack-depth.txt b/quick-sort/output/10-stack-depth.txt new file mode 100644 index 0000000..e6788f4 --- /dev/null +++ b/quick-sort/output/10-stack-depth.txt @@ -0,0 +1,9 @@ +Sorted input, n = 100,000, on a thread with a 256 KB stack +========================================================== + +Lomuto.sort (recurse into both sides): StackOverflowError +StackSafe.sort (smaller side first): sorted, deepest recursion = 2 +log2(100000) = 16.6 + +The depth at which a StackOverflowError appears depends on the JVM, the JIT state and -Xss; +what is stable is that plain recursion needs ~n frames here and StackSafe needs at most about log2(n). diff --git a/quick-sort/output/11-random-agreement.txt b/quick-sort/output/11-random-agreement.txt new file mode 100644 index 0000000..b33cc96 --- /dev/null +++ b/quick-sort/output/11-random-agreement.txt @@ -0,0 +1,10 @@ +20,000 seeded random arrays (length 0..40, keys -20..20) per version, compared with Arrays.sort +=============================================================================================== + +Lomuto 20,000 arrays, 0 disagreements +Hoare 20,000 arrays, 0 disagreements +ThreeWay 20,000 arrays, 0 disagreements +Randomized (seed 1) 20,000 arrays, 0 disagreements +StackSafe 20,000 arrays, 0 disagreements +LomutoQuickSort2015 (post 2531) 20,000 arrays, 0 disagreements +FirstPivot, fixed (post 2530) 20,000 arrays, 0 disagreements diff --git a/quick-sort/output/12-pitfalls.txt b/quick-sort/output/12-pitfalls.txt new file mode 100644 index 0000000..99f8fb9 --- /dev/null +++ b/quick-sort/output/12-pitfalls.txt @@ -0,0 +1,14 @@ +Hoare mistakes that look reasonable +=================================== + +1. last element as pivot with Hoare's (lo,p) / (p+1,hi) recursion, input [1, 2]: + StackOverflowError (the partition returns p = 1 = hi, so (lo, p) is the same range again) + +2. Hoare partition, but recursing on (lo, p-1) and (p+1, hi) as Lomuto does, input [2, 3, 1]: + result [2, 1, 3] (expected [1, 2, 3]) + + all 6 permutations of 1..3: 1 come back unsorted + all 24 permutations of 1..4: 8 come back unsorted + all 120 permutations of 1..5: 52 come back unsorted + +the real Hoare.sort on the same input: [1, 2, 3] diff --git a/quick-sort/output/13-jdk-source.txt b/quick-sort/output/13-jdk-source.txt new file mode 100644 index 0000000..8297c57 --- /dev/null +++ b/quick-sort/output/13-jdk-source.txt @@ -0,0 +1,21 @@ +What Arrays.sort really does (read from this JDK's lib/src.zip) +=============================================================== + +JDK: 25.0.5.1+2-LTS + +java/util/Arrays.java: + 99 DualPivotQuicksort.sort(a, 0, 0, a.length); + 1034 public static void sort(Object[] a) { + 1223 public static void sort(T[] a, Comparator c) { + 1038 ComparableTimSort.sort(a, 0, a.length, null, 0, 0); (inside sort(Object[])) +lines in Arrays.java that call TimSort.sort(: 8 + +java/util/DualPivotQuicksort.java, the constants and the fallback: + 69 private static final int MAX_INSERTION_SORT_SIZE = 44; + 64 private static final int MAX_MIXED_INSERTION_SORT_SIZE = 65; + 119 private static final int DELTA = 3 << 1; + 124 private static final int MAX_RECURSION_DEPTH = 64 * DELTA; + 285 if ((bits += DELTA) > MAX_RECURSION_DEPTH) { + 286 heapSort(a, low, high); + 287 return; + 288 } diff --git a/quick-sort/output/14-single-file-sessions.txt b/quick-sort/output/14-single-file-sessions.txt new file mode 100644 index 0000000..84db6da --- /dev/null +++ b/quick-sort/output/14-single-file-sessions.txt @@ -0,0 +1,24 @@ +java download/QuickSort.java, with the sample inputs of the three 2015 posts +============================================================================ + +session: 7 elements (post 2559) + Enter the size of array: Enter 7 elements (one per line): + Before: [15, 32, 45, 25, 34, 29, 14] + Lomuto: [14, 15, 25, 29, 32, 34, 45] + Hoare: [14, 15, 25, 29, 32, 34, 45] + Randomized: [14, 15, 25, 29, 32, 34, 45] + +session: 9 elements with duplicates (post 2530) + Enter the size of array: Enter 9 elements (one per line): + Before: [15, 48, 66, 12, 48, 74, 12, 24, 56] + Lomuto: [12, 12, 15, 24, 48, 48, 56, 66, 74] + Hoare: [12, 12, 15, 24, 48, 48, 56, 66, 74] + Randomized: [12, 12, 15, 24, 48, 48, 56, 66, 74] + +session: 6 elements (post 2531) + Enter the size of array: Enter 6 elements (one per line): + Before: [15, 34, 26, 67, 95, 24] + Lomuto: [15, 24, 26, 34, 67, 95] + Hoare: [15, 24, 26, 34, 67, 95] + Randomized: [15, 24, 26, 34, 67, 95] + diff --git a/quick-sort/pom.xml b/quick-sort/pom.xml new file mode 100644 index 0000000..81f67a5 --- /dev/null +++ b/quick-sort/pom.xml @@ -0,0 +1,63 @@ + + + 4.0.0 + com.ankurm.interviewlab + quick-sort + 1.0.0 + jar + + java-interview-lab :: quick-sort + + Runnable companion code for ankurm.com's "Quick Sort in Java" article: Lomuto and Hoare partition, dry runs, worst case, randomized pivot, three-way partition, stack depth, and the three 2015 programs it replaces. + + + + 25 + UTF-8 + 6.1.3 + + + + + + org.junit + junit-bom + ${junit.version} + pom + import + + + + + + + org.junit.jupiter + junit-jupiter + test + + + org.junit.platform + junit-platform-launcher + test + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.14.0 + + + org.apache.maven.plugins + maven-surefire-plugin + 3.6.0 + + -Xmx512m -Duser.timezone=UTC -Dfile.encoding=UTF-8 + + + + + diff --git a/quick-sort/scripts/run-all.sh b/quick-sort/scripts/run-all.sh new file mode 100755 index 0000000..38df9a6 --- /dev/null +++ b/quick-sort/scripts/run-all.sh @@ -0,0 +1,9 @@ +#!/usr/bin/env bash +# Regenerates every file in output/. Needs JDK 25 and Maven. The first Maven run must be online. +# Every file is written by a JUnit test that asserts the same numbers it prints, so the figures +# in the article are assertions: they fail the build the moment they stop being true. +set -euo pipefail +cd "$(dirname "$0")/.." +mkdir -p output +mvn -B -q -T1 test +echo "done:"; ls -1 output diff --git a/quick-sort/src/main/java/com/ankurm/interviewlab/quicksort/DryRuns.java b/quick-sort/src/main/java/com/ankurm/interviewlab/quicksort/DryRuns.java new file mode 100644 index 0000000..055f5ad --- /dev/null +++ b/quick-sort/src/main/java/com/ankurm/interviewlab/quicksort/DryRuns.java @@ -0,0 +1,85 @@ +package com.ankurm.interviewlab.quicksort; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +/** Instrumented copies of both partitions that record every step, for the dry-run tables in the article. */ +public final class DryRuns { + private DryRuns() {} + + public record Trace(List lines, int partitionCalls) {} + + public static Trace lomuto(int[] input) { + int[] a = input.clone(); + List out = new ArrayList<>(); + int[] calls = {0}; + lomuto(a, 0, a.length - 1, 0, out, calls); + out.add("final: " + Arrays.toString(a)); + return new Trace(out, calls[0]); + } + + private static void lomuto(int[] a, int lo, int hi, int depth, List out, int[] calls) { + if (lo >= hi) { + return; + } + calls[0]++; + String pad = " ".repeat(depth); + int pivot = a[hi]; + out.add(pad + "partition [" + lo + ".." + hi + "] " + Arrays.toString(Arrays.copyOfRange(a, lo, hi + 1)) + ", pivot = " + pivot + " (last)"); + int i = lo - 1; + for (int j = lo; j < hi; j++) { + if (a[j] <= pivot) { + i++; + Lomuto.swap(a, i, j); + out.add(pad + " j=" + j + ": " + a[i] + " <= " + pivot + " -> i=" + i + ", swap a[" + i + "] and a[" + j + "] " + Arrays.toString(a)); + } else { + out.add(pad + " j=" + j + ": " + a[j] + " > " + pivot + " -> skip"); + } + } + Lomuto.swap(a, i + 1, hi); + out.add(pad + " place pivot: swap a[" + (i + 1) + "] and a[" + hi + "] " + Arrays.toString(a) + " -> pivot final at index " + (i + 1)); + lomuto(a, lo, i, depth + 1, out, calls); + lomuto(a, i + 2, hi, depth + 1, out, calls); + } + + public static Trace hoare(int[] input) { + int[] a = input.clone(); + List out = new ArrayList<>(); + int[] calls = {0}; + hoare(a, 0, a.length - 1, 0, out, calls); + out.add("final: " + Arrays.toString(a)); + return new Trace(out, calls[0]); + } + + private static void hoare(int[] a, int lo, int hi, int depth, List out, int[] calls) { + if (lo >= hi) { + return; + } + calls[0]++; + String pad = " ".repeat(depth); + int mid = lo + (hi - lo) / 2; + int pivot = a[mid]; + out.add(pad + "partition [" + lo + ".." + hi + "] " + Arrays.toString(Arrays.copyOfRange(a, lo, hi + 1)) + ", pivot = " + pivot + " (middle, index " + mid + ")"); + int i = lo - 1; + int j = hi + 1; + int p; + while (true) { + do { i++; } while (a[i] < pivot); + do { j--; } while (a[j] > pivot); + if (i >= j) { + p = j; + out.add(pad + " i=" + i + " j=" + j + " pointers met/crossed -> split after index " + p); + break; + } + out.add(pad + " i stops at " + i + " (" + a[i] + "), j stops at " + j + " (" + a[j] + ") -> swap " + swapped(a, i, j)); + } + hoare(a, lo, p, depth + 1, out, calls); + hoare(a, p + 1, hi, depth + 1, out, calls); + } + + private static String swapped(int[] a, int i, int j) { + Lomuto.swap(a, i, j); + return Arrays.toString(a); + } +} diff --git a/quick-sort/src/main/java/com/ankurm/interviewlab/quicksort/Hoare.java b/quick-sort/src/main/java/com/ankurm/interviewlab/quicksort/Hoare.java new file mode 100644 index 0000000..848b4ec --- /dev/null +++ b/quick-sort/src/main/java/com/ankurm/interviewlab/quicksort/Hoare.java @@ -0,0 +1,38 @@ +package com.ankurm.interviewlab.quicksort; + +/** + * Quick Sort with Hoare's original partition (1959-61): two pointers walk towards each other and swap + * the pair that is on the wrong side. Fewer swaps than Lomuto, and it splits runs of equal keys evenly. + * + *

The returned index is NOT the pivot's final position. It only says "everything in [lo..p] is <= + * everything in [p+1..hi]", so the recursion is (lo, p) and (p + 1, hi), never (p - 1) and (p + 1). + */ +public final class Hoare { + private Hoare() {} + + public static int partition(int[] a, int lo, int hi) { + int pivot = a[lo + (hi - lo) / 2]; // middle element, rounded DOWN: see Pitfalls for why that matters + int i = lo - 1; + int j = hi + 1; + while (true) { + do { i++; } while (a[i] < pivot); // stops on a key >= pivot + do { j--; } while (a[j] > pivot); // stops on a key <= pivot + if (i >= j) { + return j; + } + Lomuto.swap(a, i, j); + } + } + + public static void sort(int[] a) { + sort(a, 0, a.length - 1); + } + + public static void sort(int[] a, int lo, int hi) { + if (lo < hi) { + int p = partition(a, lo, hi); + sort(a, lo, p); // p belongs to the LEFT part here + sort(a, p + 1, hi); + } + } +} diff --git a/quick-sort/src/main/java/com/ankurm/interviewlab/quicksort/Lomuto.java b/quick-sort/src/main/java/com/ankurm/interviewlab/quicksort/Lomuto.java new file mode 100644 index 0000000..38d063e --- /dev/null +++ b/quick-sort/src/main/java/com/ankurm/interviewlab/quicksort/Lomuto.java @@ -0,0 +1,41 @@ +package com.ankurm.interviewlab.quicksort; + +/** + * Quick Sort with the Lomuto partition: the last element is the pivot, one pointer ({@code i}) marks the + * end of the "small" zone and one ({@code j}) scans. Simple to explain, which is why textbooks use it. + */ +public final class Lomuto { + private Lomuto() {} + + /** Puts a[hi] (the pivot) in its final position and returns that index. Elements <= pivot end up on its left. */ + public static int partition(int[] a, int lo, int hi) { + int pivot = a[hi]; + int i = lo - 1; // last index of the "<= pivot" zone + for (int j = lo; j < hi; j++) { + if (a[j] <= pivot) { + i++; + swap(a, i, j); + } + } + swap(a, i + 1, hi); // drop the pivot between the two zones + return i + 1; + } + + public static void sort(int[] a) { + sort(a, 0, a.length - 1); + } + + public static void sort(int[] a, int lo, int hi) { + if (lo < hi) { + int p = partition(a, lo, hi); + sort(a, lo, p - 1); // the pivot is final: it is excluded from both sides + sort(a, p + 1, hi); + } + } + + static void swap(int[] a, int i, int j) { + int t = a[i]; + a[i] = a[j]; + a[j] = t; + } +} diff --git a/quick-sort/src/main/java/com/ankurm/interviewlab/quicksort/Measured.java b/quick-sort/src/main/java/com/ankurm/interviewlab/quicksort/Measured.java new file mode 100644 index 0000000..1bbcc20 --- /dev/null +++ b/quick-sort/src/main/java/com/ankurm/interviewlab/quicksort/Measured.java @@ -0,0 +1,105 @@ +package com.ankurm.interviewlab.quicksort; + +import java.util.Random; + +/** + * Instrumented copies of the sorts. They count what the article talks about (comparisons of an element + * with the pivot, swaps between two different positions, deepest recursion) and are cross-checked + * against Arrays.sort, so the counting cannot silently change the algorithm. + */ +public final class Measured { + public enum Scheme { LOMUTO_LAST, LOMUTO_RANDOM, HOARE_MIDDLE, THREE_WAY } + + public record Result(long comparisons, long swaps, int maxDepth) {} + + private long comparisons; + private long swaps; + private int maxDepth; + private final Random rnd; + + private Measured(long seed) { + rnd = new Random(seed); + } + + public static Result run(Scheme scheme, int[] a) { + return run(scheme, a, 42); + } + + /** The seed only matters for LOMUTO_RANDOM. */ + public static Result run(Scheme scheme, int[] a, long seed) { + Measured m = new Measured(seed); + m.sort(scheme, a, 0, a.length - 1, 1); + return new Result(m.comparisons, m.swaps, m.maxDepth); + } + + private void swap(int[] a, int i, int j) { + if (i != j) { + swaps++; + Lomuto.swap(a, i, j); + } + } + + private void sort(Scheme s, int[] a, int lo, int hi, int depth) { + maxDepth = Math.max(maxDepth, depth); + if (lo >= hi) { + return; + } + switch (s) { + case LOMUTO_LAST, LOMUTO_RANDOM -> { + if (s == Scheme.LOMUTO_RANDOM) { + swap(a, lo + rnd.nextInt(hi - lo + 1), hi); + } + int pivot = a[hi]; + int i = lo - 1; + for (int j = lo; j < hi; j++) { + comparisons++; + if (a[j] <= pivot) { + i++; + swap(a, i, j); + } + } + swap(a, i + 1, hi); + sort(s, a, lo, i, depth + 1); + sort(s, a, i + 2, hi, depth + 1); + } + case HOARE_MIDDLE -> { + int pivot = a[lo + (hi - lo) / 2]; + int i = lo - 1; + int j = hi + 1; + int p; + while (true) { + do { i++; comparisons++; } while (a[i] < pivot); + do { j--; comparisons++; } while (a[j] > pivot); + if (i >= j) { + p = j; + break; + } + swap(a, i, j); + } + sort(s, a, lo, p, depth + 1); + sort(s, a, p + 1, hi, depth + 1); + } + case THREE_WAY -> { + int pivot = a[lo + (hi - lo) / 2]; + int lt = lo; + int i = lo; + int gt = hi; + while (i <= gt) { + comparisons++; + if (a[i] < pivot) { + swap(a, lt++, i++); + } else { + comparisons++; + if (a[i] > pivot) { + swap(a, i, gt--); + } else { + i++; + } + } + } + sort(s, a, lo, lt - 1, depth + 1); + sort(s, a, gt + 1, hi, depth + 1); + } + } + } +} diff --git a/quick-sort/src/main/java/com/ankurm/interviewlab/quicksort/Pitfalls.java b/quick-sort/src/main/java/com/ankurm/interviewlab/quicksort/Pitfalls.java new file mode 100644 index 0000000..a394ce9 --- /dev/null +++ b/quick-sort/src/main/java/com/ankurm/interviewlab/quicksort/Pitfalls.java @@ -0,0 +1,36 @@ +package com.ankurm.interviewlab.quicksort; + +/** Plausible-looking Hoare variants that are wrong. Each one is reproduced in PitfallsTest. */ +public final class Pitfalls { + private Pitfalls() {} + + /** Hoare partition with the LAST element as pivot, recursing on (lo, p) and (p + 1, hi): never terminates on [1, 2]. */ + public static void hoareLastPivotLeftIncludesP(int[] a, int lo, int hi) { + if (lo < hi) { + int pivot = a[hi]; + int i = lo - 1; + int j = hi + 1; + int p; + while (true) { + do { i++; } while (a[i] < pivot); + do { j--; } while (a[j] > pivot); + if (i >= j) { + p = j; + break; + } + Lomuto.swap(a, i, j); + } + hoareLastPivotLeftIncludesP(a, lo, p); + hoareLastPivotLeftIncludesP(a, p + 1, hi); + } + } + + /** Correct Hoare partition, but recursing on (lo, p - 1) and (p + 1, hi) as if p were the pivot's final slot: loses sorting. */ + public static void hoareTreatsPAsPivotSlot(int[] a, int lo, int hi) { + if (lo < hi) { + int p = Hoare.partition(a, lo, hi); + hoareTreatsPAsPivotSlot(a, lo, p - 1); + hoareTreatsPAsPivotSlot(a, p + 1, hi); + } + } +} diff --git a/quick-sort/src/main/java/com/ankurm/interviewlab/quicksort/Randomized.java b/quick-sort/src/main/java/com/ankurm/interviewlab/quicksort/Randomized.java new file mode 100644 index 0000000..32f6a23 --- /dev/null +++ b/quick-sort/src/main/java/com/ankurm/interviewlab/quicksort/Randomized.java @@ -0,0 +1,21 @@ +package com.ankurm.interviewlab.quicksort; + +import java.util.Random; + +/** Lomuto with a random pivot: swap a random element into the last slot, then partition as usual. */ +public final class Randomized { + private Randomized() {} + + public static void sort(int[] a, Random rnd) { + sort(a, 0, a.length - 1, rnd); + } + + public static void sort(int[] a, int lo, int hi, Random rnd) { + if (lo < hi) { + Lomuto.swap(a, lo + rnd.nextInt(hi - lo + 1), hi); + int p = Lomuto.partition(a, lo, hi); + sort(a, lo, p - 1, rnd); + sort(a, p + 1, hi, rnd); + } + } +} diff --git a/quick-sort/src/main/java/com/ankurm/interviewlab/quicksort/StackSafe.java b/quick-sort/src/main/java/com/ankurm/interviewlab/quicksort/StackSafe.java new file mode 100644 index 0000000..deec9e5 --- /dev/null +++ b/quick-sort/src/main/java/com/ankurm/interviewlab/quicksort/StackSafe.java @@ -0,0 +1,29 @@ +package com.ankurm.interviewlab.quicksort; + +/** + * Recurse into the SMALLER side, loop on the larger one. Each recursive call at least halves the range, + * so the stack never holds more than log2(n) frames, whatever the pivot does. + */ +public final class StackSafe { + private StackSafe() {} + + /** Sorts with Lomuto partitioning and returns the deepest recursion reached (outermost call = 1). */ + public static int sort(int[] a) { + return sort(a, 0, a.length - 1, 1); + } + + private static int sort(int[] a, int lo, int hi, int depth) { + int deepest = depth; + while (lo < hi) { + int p = Lomuto.partition(a, lo, hi); + if (p - lo < hi - p) { + deepest = Math.max(deepest, sort(a, lo, p - 1, depth + 1)); + lo = p + 1; // keep looping on the right (larger) side + } else { + deepest = Math.max(deepest, sort(a, p + 1, hi, depth + 1)); + hi = p - 1; // keep looping on the left (larger) side + } + } + return deepest; + } +} diff --git a/quick-sort/src/main/java/com/ankurm/interviewlab/quicksort/ThreeWay.java b/quick-sort/src/main/java/com/ankurm/interviewlab/quicksort/ThreeWay.java new file mode 100644 index 0000000..08ad40b --- /dev/null +++ b/quick-sort/src/main/java/com/ankurm/interviewlab/quicksort/ThreeWay.java @@ -0,0 +1,31 @@ +package com.ankurm.interviewlab.quicksort; + +/** Dijkstra's three-way partition (Dutch national flag): < pivot | == pivot | > pivot. Equal keys are never revisited. */ +public final class ThreeWay { + private ThreeWay() {} + + public static void sort(int[] a) { + sort(a, 0, a.length - 1); + } + + public static void sort(int[] a, int lo, int hi) { + if (lo >= hi) { + return; + } + int pivot = a[lo + (hi - lo) / 2]; + int lt = lo; // a[lo..lt-1] < pivot + int i = lo; // a[lt..i-1] == pivot, a[i..gt] not yet looked at + int gt = hi; // a[gt+1..hi] > pivot + while (i <= gt) { + if (a[i] < pivot) { + Lomuto.swap(a, lt++, i++); + } else if (a[i] > pivot) { + Lomuto.swap(a, i, gt--); + } else { + i++; + } + } + sort(a, lo, lt - 1); + sort(a, gt + 1, hi); + } +} diff --git a/quick-sort/src/main/java/com/ankurm/interviewlab/quicksort/legacy/FirstPivotQuickSort.java b/quick-sort/src/main/java/com/ankurm/interviewlab/quicksort/legacy/FirstPivotQuickSort.java new file mode 100644 index 0000000..c852de8 --- /dev/null +++ b/quick-sort/src/main/java/com/ankurm/interviewlab/quicksort/legacy/FirstPivotQuickSort.java @@ -0,0 +1,68 @@ +package com.ankurm.interviewlab.quicksort.legacy; + +/** + * The first 2015 "Implementing Quicksort Algorithm in Java" program, logic unchanged: first element as + * pivot, two pointers. {@link #partition} keeps the original loop condition {@code x[i] <= y && i <= r}; + * {@link #partitionFixed} swaps the two operands, which is the whole fix. + */ +public final class FirstPivotQuickSort { + private FirstPivotQuickSort() {} + + public static int partition(int[] x, int l, int r) { + int i = l; + int j = r; + int y = x[l]; + while (i < j) { + while (x[i] <= y && i <= r) // original: reads x[i] BEFORE checking i <= r + i++; + while (x[j] > y) + j--; + if (i < j) { + int t = x[i]; + x[i] = x[j]; + x[j] = t; + } + } + int t = x[j]; + x[j] = x[l]; + x[l] = t; + return j; + } + + public static int partitionFixed(int[] x, int l, int r) { + int i = l; + int j = r; + int y = x[l]; + while (i < j) { + while (i <= r && x[i] <= y) // fixed: bounds check first + i++; + while (x[j] > y) + j--; + if (i < j) { + int t = x[i]; + x[i] = x[j]; + x[j] = t; + } + } + int t = x[j]; + x[j] = x[l]; + x[l] = t; + return j; + } + + public static void sort(int[] x, int l, int r) { + if (l < r) { + int p = partition(x, l, r); + sort(x, l, p - 1); + sort(x, p + 1, r); + } + } + + public static void sortFixed(int[] x, int l, int r) { + if (l < r) { + int p = partitionFixed(x, l, r); + sortFixed(x, l, p - 1); + sortFixed(x, p + 1, r); + } + } +} diff --git a/quick-sort/src/main/java/com/ankurm/interviewlab/quicksort/legacy/LomutoQuickSort2015.java b/quick-sort/src/main/java/com/ankurm/interviewlab/quicksort/legacy/LomutoQuickSort2015.java new file mode 100644 index 0000000..d3620df --- /dev/null +++ b/quick-sort/src/main/java/com/ankurm/interviewlab/quicksort/legacy/LomutoQuickSort2015.java @@ -0,0 +1,42 @@ +package com.ankurm.interviewlab.quicksort.legacy; + +/** + * The second 2015 "Implementing Quicksort Algorithm in Java" program, logic unchanged (static field and the + * redundant {@code a = ta} kept). It is the Lomuto partition with the last element as pivot. + */ +public final class LomutoQuickSort2015 { + static protected int[] a; + + private LomutoQuickSort2015() {} + + public static void sort(int[] input) { + a = input; + quicksort(a, 0, input.length - 1); + } + + static void quicksort(int[] t, int p, int r) { + if (p < r) { + int q = partition(t, p, r); + quicksort(t, p, q - 1); + quicksort(t, q + 1, r); + } + } + + static int partition(int[] ta, int l, int h) { + int x = ta[h]; + int i = l - 1; + for (int j = l; j <= h - 1; j++) { + if (ta[j] <= x) { + i = i + 1; + int temp = ta[j]; + ta[j] = ta[i]; + ta[i] = temp; + } + } + int temp2 = ta[i + 1]; + ta[i + 1] = ta[h]; + ta[h] = temp2; + a = ta; + return (i + 1); + } +} diff --git a/quick-sort/src/main/java/com/ankurm/interviewlab/quicksort/legacy/TempArrayQuickSort.java b/quick-sort/src/main/java/com/ankurm/interviewlab/quicksort/legacy/TempArrayQuickSort.java new file mode 100644 index 0000000..7a06e47 --- /dev/null +++ b/quick-sort/src/main/java/com/ankurm/interviewlab/quicksort/legacy/TempArrayQuickSort.java @@ -0,0 +1,51 @@ +package com.ankurm.interviewlab.quicksort.legacy; + +/** + * The 2015 "Implementing Quick Sort in Java" algorithm, logic unchanged (only the class is made reusable): + * first element as pivot, a temporary array of the WHOLE array's size on every call, three passes. + * Strictly smaller goes left, strictly larger goes right, and nothing handles keys equal to the pivot. + */ +public final class TempArrayQuickSort { + private final int[] array; + private final int size; + + public TempArrayQuickSort(int[] inputArray) { + array = inputArray; + size = array.length; + } + + public void sort() { + sortPartition(0, size - 1); + } + + private void sortPartition(int lb, int ub) { + if (lb >= ub) return; + + int[] temp = new int[size]; + int tempIndex = lb; + int pivot = array[lb]; + + for (int i = lb; i <= ub; i++) { + if (pivot > array[i]) { + temp[tempIndex] = array[i]; + tempIndex++; + } + } + int pivotIndex = tempIndex; + temp[tempIndex] = pivot; + tempIndex++; + for (int i = lb; i <= ub; i++) { + if (pivot < array[i]) { + temp[tempIndex] = array[i]; + tempIndex++; + } + } + for (int i = lb; i <= ub; i++) { + array[i] = temp[i]; + } + if (lb < ub) { + sortPartition(lb, pivotIndex - 1); + sortPartition(pivotIndex + 1, ub); + } + } +} diff --git a/quick-sort/src/test/java/com/ankurm/interviewlab/quicksort/AgreementTest.java b/quick-sort/src/test/java/com/ankurm/interviewlab/quicksort/AgreementTest.java new file mode 100644 index 0000000..a11edc4 --- /dev/null +++ b/quick-sort/src/test/java/com/ankurm/interviewlab/quicksort/AgreementTest.java @@ -0,0 +1,52 @@ +package com.ankurm.interviewlab.quicksort; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import com.ankurm.interviewlab.quicksort.legacy.FirstPivotQuickSort; +import com.ankurm.interviewlab.quicksort.legacy.LomutoQuickSort2015; +import com.ankurm.interviewlab.quicksort.support.Transcript; +import java.util.Arrays; +import java.util.Locale; +import java.util.Random; +import java.util.function.Consumer; +import org.junit.jupiter.api.Test; + +/** Every sort that claims to be correct, against Arrays.sort, on seeded random arrays full of duplicates. */ +class AgreementTest { + + @Test + void everyCorrectVersionAgreesWithArraysSort() { + record Variant(String name, Consumer sort) {} + Variant[] variants = { + new Variant("Lomuto", Lomuto::sort), + new Variant("Hoare", Hoare::sort), + new Variant("ThreeWay", ThreeWay::sort), + new Variant("Randomized (seed 1)", a -> Randomized.sort(a, new Random(1))), + new Variant("StackSafe", StackSafe::sort), + new Variant("LomutoQuickSort2015 (post 2531)", LomutoQuickSort2015::sort), + new Variant("FirstPivot, fixed (post 2530)", a -> FirstPivotQuickSort.sortFixed(a, 0, a.length - 1)), + }; + int arrays = 20_000; + Transcript t = Transcript.start("11-random-agreement.txt", String.format(Locale.ROOT, "%,d seeded random arrays (length 0..40, keys -20..20) per version, compared with Arrays.sort", arrays)); + for (Variant v : variants) { + Random r = new Random(11); + int disagreements = 0; + for (int k = 0; k < arrays; k++) { + int n = r.nextInt(41); + int[] a = new int[n]; + for (int i = 0; i < n; i++) { + a[i] = r.nextInt(41) - 20; + } + int[] expected = a.clone(); + Arrays.sort(expected); + v.sort().accept(a); + if (!Arrays.equals(expected, a)) { + disagreements++; + } + } + assertEquals(0, disagreements, v.name()); + t.line(String.format(Locale.ROOT, "%-34s %,d arrays, %d disagreements", v.name(), arrays, disagreements)); + } + t.flush(); + } +} diff --git a/quick-sort/src/test/java/com/ankurm/interviewlab/quicksort/ComplexityTest.java b/quick-sort/src/test/java/com/ankurm/interviewlab/quicksort/ComplexityTest.java new file mode 100644 index 0000000..17a597b --- /dev/null +++ b/quick-sort/src/test/java/com/ankurm/interviewlab/quicksort/ComplexityTest.java @@ -0,0 +1,147 @@ +package com.ankurm.interviewlab.quicksort; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import com.ankurm.interviewlab.quicksort.Measured.Result; +import com.ankurm.interviewlab.quicksort.Measured.Scheme; +import com.ankurm.interviewlab.quicksort.support.Data; +import com.ankurm.interviewlab.quicksort.support.Transcript; +import java.util.Arrays; +import java.util.LinkedHashMap; +import java.util.Locale; +import java.util.Map; +import org.junit.jupiter.api.Test; + +/** Comparison, swap and depth counts. Exact where the maths is exact, bounds where it is statistical. */ +class ComplexityTest { + static final int N = 5000; + static final long QUADRATIC = (long) N * (N - 1) / 2; + + /** The quadratic cases recurse n deep, so run on a thread with a generous stack: the counts must not depend on how much stack the test runner happens to give us. */ + private static Result onBigStack(Scheme s, int[] a, long seed) { + Result[] out = new Result[1]; + Throwable failure = Data.runWithStack(256L * 1024 * 1024, () -> out[0] = Measured.run(s, a, seed)); + if (failure != null) { + throw new AssertionError(failure); + } + return out[0]; + } + + private static Result measured(Scheme s, int[] input) { + int[] a = input.clone(); + Result r = onBigStack(s, a, 42); + int[] expected = input.clone(); + Arrays.sort(expected); + assertArrayEquals(expected, a, s + " must still sort"); + return r; + } + + @Test + void worstCaseMatrix() { + Map inputs = new LinkedHashMap<>(); + inputs.put("random", Data.random(N, 7)); + inputs.put("already sorted", Data.sorted(N)); + inputs.put("reverse sorted", Data.reversed(N)); + inputs.put("all equal", Data.allEqual(N)); + inputs.put("10 distinct keys", Data.fewUnique(N, 7)); + + Transcript t = Transcript.start("06-worst-case.txt", "Comparisons / swaps / deepest recursion, n = " + N); + t.line("n(n-1)/2 = " + String.format(Locale.ROOT, "%,d", QUADRATIC) + " (what 'quadratic' means for this n)").blank(); + t.line(String.format(Locale.ROOT, "%-18s %-14s %12s %10s %8s", "input", "scheme", "comparisons", "swaps", "depth")); + for (var in : inputs.entrySet()) { + for (Scheme s : Scheme.values()) { + Result r = measured(s, in.getValue()); + t.line(String.format(Locale.ROOT, "%-18s %-14s %,12d %,10d %,8d", in.getKey(), s, r.comparisons(), r.swaps(), r.maxDepth())); + } + t.blank(); + } + t.flush(); + + // Exact: with the last element as pivot, sorted / reverse / all-equal each leave one side empty every time. + for (String k : new String[] {"already sorted", "reverse sorted", "all equal"}) { + Result r = measured(Scheme.LOMUTO_LAST, inputs.get(k)); + assertEquals(QUADRATIC, r.comparisons(), k); + assertEquals(N, r.maxDepth(), k + ": recursion as deep as the array is long"); + } + // The middle pivot makes sorted and reverse-sorted input easy... + assertTrue(measured(Scheme.HOARE_MIDDLE, inputs.get("already sorted")).comparisons() < 20L * N); + assertTrue(measured(Scheme.HOARE_MIDDLE, inputs.get("reverse sorted")).comparisons() < 20L * N); + // ...and Hoare does not blow up on equal keys, because both pointers stop on them. + assertTrue(measured(Scheme.HOARE_MIDDLE, inputs.get("all equal")).comparisons() < 20L * N); + // A random pivot fixes sorted input but NOT all-equal input: every key is "<= pivot" whatever the pivot is. + assertTrue(measured(Scheme.LOMUTO_RANDOM, inputs.get("already sorted")).comparisons() < 20L * N); + assertEquals(QUADRATIC, measured(Scheme.LOMUTO_RANDOM, inputs.get("all equal")).comparisons()); + // Three-way partition looks at each key twice (once for <, once for >) and is done: no recursion left. + Result w = measured(Scheme.THREE_WAY, inputs.get("all equal")); + assertEquals(2L * N, w.comparisons()); + assertEquals(0, w.swaps()); + } + + @Test + void lomutoVersusHoareOnRandomInput() { + Transcript t = Transcript.start("07-lomuto-vs-hoare-random.txt", "Lomuto vs Hoare on random distinct-ish keys (seed 7)"); + t.line(String.format(Locale.ROOT, "%-10s %-14s %14s %12s", "n", "scheme", "comparisons", "swaps")); + for (int n : new int[] {1_000, 10_000, 100_000}) { + int[] data = Data.random(n, 7); + Result lomuto = measured(Scheme.LOMUTO_LAST, data); + Result hoare = measured(Scheme.HOARE_MIDDLE, data); + t.line(String.format(Locale.ROOT, "%,-10d %-14s %,14d %,12d", n, Scheme.LOMUTO_LAST, lomuto.comparisons(), lomuto.swaps())); + t.line(String.format(Locale.ROOT, "%,-10d %-14s %,14d %,12d", n, Scheme.HOARE_MIDDLE, hoare.comparisons(), hoare.swaps())); + t.line(String.format(Locale.ROOT, "%10s Hoare used %.2fx the swaps of Lomuto", "", (double) hoare.swaps() / lomuto.swaps())).blank(); + assertTrue(hoare.swaps() < lomuto.swaps(), "n=" + n); + } + t.flush(); + } + + @Test + void randomPivotBeatsSortedInputForEverySeed() { + int[] sorted = Data.sorted(N); + long min = Long.MAX_VALUE; + long max = 0; + int deepest = 0; + Transcript t = Transcript.start("08-randomized-pivot.txt", "Random pivot on already-sorted input, n = " + N + ", seeds 1..20"); + t.line("Lomuto, last element as pivot: " + String.format(Locale.ROOT, "%,d", measured(Scheme.LOMUTO_LAST, sorted).comparisons()) + " comparisons").blank(); + for (long seed = 1; seed <= 20; seed++) { + int[] a = sorted.clone(); + Result r = onBigStack(Scheme.LOMUTO_RANDOM, a, seed); + assertTrue(isSorted(a)); + min = Math.min(min, r.comparisons()); + max = Math.max(max, r.comparisons()); + deepest = Math.max(deepest, r.maxDepth()); + t.line(String.format(Locale.ROOT, "seed %2d: %,8d comparisons, depth %d", seed, r.comparisons(), r.maxDepth())); + } + t.blank().line(String.format(Locale.ROOT, "over 20 seeds: min %,d, max %,d comparisons, deepest recursion %d", min, max, deepest)); + t.line(String.format(Locale.ROOT, "n * log2(n) = %,.0f", N * (Math.log(N) / Math.log(2)))); + t.flush(); + assertTrue(max < 4L * N * 13, "far below quadratic for every seed"); + assertTrue(max < QUADRATIC / 20); + } + + @Test + void threeWayPartitionOnManyDuplicates() { + int[] few = Data.fewUnique(20_000, 7); + Transcript t = Transcript.start("09-three-way-duplicates.txt", "20,000 keys drawn from only 10 distinct values"); + t.line(String.format(Locale.ROOT, "%-14s %16s %12s %8s", "scheme", "comparisons", "swaps", "depth")); + Result l = measured(Scheme.LOMUTO_LAST, few); + Result h = measured(Scheme.HOARE_MIDDLE, few); + Result w = measured(Scheme.THREE_WAY, few); + for (var e : Map.of(Scheme.LOMUTO_LAST, l, Scheme.HOARE_MIDDLE, h, Scheme.THREE_WAY, w).entrySet().stream() + .sorted(java.util.Map.Entry.comparingByKey()).toList()) { + t.line(String.format(Locale.ROOT, "%-14s %,16d %,12d %,8d", e.getKey(), e.getValue().comparisons(), e.getValue().swaps(), e.getValue().maxDepth())); + } + t.flush(); + assertTrue(w.comparisons() < h.comparisons()); + assertTrue(w.comparisons() < l.comparisons() / 50, "three-way is orders of magnitude cheaper than Lomuto here"); + } + + private static boolean isSorted(int[] a) { + for (int i = 1; i < a.length; i++) { + if (a[i - 1] > a[i]) { + return false; + } + } + return true; + } +} diff --git a/quick-sort/src/test/java/com/ankurm/interviewlab/quicksort/DryRunTest.java b/quick-sort/src/test/java/com/ankurm/interviewlab/quicksort/DryRunTest.java new file mode 100644 index 0000000..fb64081 --- /dev/null +++ b/quick-sort/src/test/java/com/ankurm/interviewlab/quicksort/DryRunTest.java @@ -0,0 +1,64 @@ +package com.ankurm.interviewlab.quicksort; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; + +import com.ankurm.interviewlab.quicksort.support.Transcript; +import java.util.Arrays; +import org.junit.jupiter.api.Test; + +/** Step-by-step traces. Each trace is cross-checked against the real (uninstrumented) code. */ +class DryRunTest { + static final int[] SAMPLE_2531 = {15, 34, 26, 67, 95, 24}; + static final int[] SAMPLE_2559 = {15, 32, 45, 25, 34, 29, 14}; + static final int[] SAMPLE_2530 = {15, 48, 66, 12, 48, 74, 12, 24, 56}; + + private static int[] sortedCopy(int[] a) { + int[] c = a.clone(); + Arrays.sort(c); + return c; + } + + @Test + void lomutoTraceOnTheSixElementSample() { + DryRuns.Trace tr = DryRuns.lomuto(SAMPLE_2531); + int[] real = SAMPLE_2531.clone(); + Lomuto.sort(real); + assertArrayEquals(sortedCopy(SAMPLE_2531), real); + assertEquals("final: " + Arrays.toString(real), tr.lines().getLast()); + Transcript t = Transcript.start("01-dry-run-lomuto.txt", "Lomuto partition, traced on " + Arrays.toString(SAMPLE_2531)); + tr.lines().forEach(t::line); + t.blank().line("partition calls: " + tr.partitionCalls()); + t.flush(); + } + + @Test + void hoareTraceOnTheSameSample() { + DryRuns.Trace tr = DryRuns.hoare(SAMPLE_2531); + int[] real = SAMPLE_2531.clone(); + Hoare.sort(real); + assertArrayEquals(sortedCopy(SAMPLE_2531), real); + assertEquals("final: " + Arrays.toString(real), tr.lines().getLast()); + Transcript t = Transcript.start("02-dry-run-hoare.txt", "Hoare partition, traced on " + Arrays.toString(SAMPLE_2531)); + tr.lines().forEach(t::line); + t.blank().line("partition calls: " + tr.partitionCalls()); + t.flush(); + } + + @Test + void bothSchemesOnTheOtherTwoSamplesFromThe2015Posts() { + Transcript t = Transcript.start("03-both-on-the-2015-samples.txt", "Both partitions on the sample inputs of the other two 2015 posts"); + for (int[] sample : new int[][] {SAMPLE_2559, SAMPLE_2530}) { + int[] l = sample.clone(); + int[] h = sample.clone(); + Lomuto.sort(l); + Hoare.sort(h); + assertArrayEquals(sortedCopy(sample), l); + assertArrayEquals(sortedCopy(sample), h); + t.line("input: " + Arrays.toString(sample)); + t.line("Lomuto: " + Arrays.toString(l) + " (" + DryRuns.lomuto(sample).partitionCalls() + " partition calls)"); + t.line("Hoare: " + Arrays.toString(h) + " (" + DryRuns.hoare(sample).partitionCalls() + " partition calls)").blank(); + } + t.flush(); + } +} diff --git a/quick-sort/src/test/java/com/ankurm/interviewlab/quicksort/JdkSourceTest.java b/quick-sort/src/test/java/com/ankurm/interviewlab/quicksort/JdkSourceTest.java new file mode 100644 index 0000000..4b9d846 --- /dev/null +++ b/quick-sort/src/test/java/com/ankurm/interviewlab/quicksort/JdkSourceTest.java @@ -0,0 +1,81 @@ +package com.ankurm.interviewlab.quicksort; + +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assumptions.assumeTrue; + +import com.ankurm.interviewlab.quicksort.support.Transcript; +import java.io.IOException; +import java.nio.file.FileSystems; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; +import org.junit.jupiter.api.Test; + +/** Reads the JDK's own source rather than trusting memory about what Arrays.sort does. */ +class JdkSourceTest { + + @Test + void whatArraysSortDoes() throws IOException { + Path zip = Path.of(System.getProperty("java.home"), "lib", "src.zip"); + assumeTrue(Files.exists(zip), "this JDK has no lib/src.zip"); + Transcript t = Transcript.start("13-jdk-source.txt", "What Arrays.sort really does (read from this JDK's lib/src.zip)"); + t.line("JDK: " + Runtime.version()).blank(); + try (var fs = FileSystems.newFileSystem(zip)) { + List dpq = Files.readAllLines(fs.getPath("java.base/java/util/DualPivotQuicksort.java")); + List arrays = Files.readAllLines(fs.getPath("java.base/java/util/Arrays.java")); + + t.line("java/util/Arrays.java:"); + boolean intSortCalls = false; + for (int i = 0; i < arrays.size(); i++) { + String l = arrays.get(i); + if (l.contains("DualPivotQuicksort.sort(a, 0, 0, a.length);")) { + t.line(String.format("%6d %s", i + 1, l.stripLeading())); + intSortCalls = true; + break; + } + } + assertTrue(intSortCalls); + for (int i = 0; i < arrays.size(); i++) { + String l = arrays.get(i); + if (l.contains("public static void sort(Object[] a)") || l.contains("public static void sort(T[] a, Comparator c)")) { + t.line(String.format("%6d %s", i + 1, l.stripLeading())); + } + } + for (int i = 0; i < arrays.size(); i++) { + if (arrays.get(i).contains("ComparableTimSort.sort(a, 0, a.length, null, 0, 0);")) { + t.line(String.format("%6d %s (inside sort(Object[]))", i + 1, arrays.get(i).strip())); + break; + } + } + long timSort = arrays.stream().filter(l -> l.contains("TimSort.sort(")).count(); + t.line("lines in Arrays.java that call TimSort.sort(: " + timSort); + assertTrue(timSort > 0); + + t.blank().line("java/util/DualPivotQuicksort.java, the constants and the fallback:"); + for (String key : new String[] {"MAX_INSERTION_SORT_SIZE =", "MAX_MIXED_INSERTION_SORT_SIZE =", "DELTA =", "MAX_RECURSION_DEPTH ="}) { + int idx = -1; + for (int i = 0; i < dpq.size(); i++) { + if (dpq.get(i).contains(key)) { + idx = i; + break; + } + } + assertTrue(idx >= 0, key); + t.line(String.format("%6d %s", idx + 1, dpq.get(idx).strip())); + } + int fb = -1; + for (int i = 0; i < dpq.size(); i++) { + if (dpq.get(i).contains("> MAX_RECURSION_DEPTH")) { + fb = i; + break; + } + } + assertTrue(fb >= 0); + for (int i = fb; i <= fb + 3; i++) { + t.line(String.format("%6d %s", i + 1, dpq.get(i).strip())); + } + assertTrue(dpq.get(fb + 1).contains("heapSort"), "the fallback is heap sort"); + } + t.flush(); + } +} diff --git a/quick-sort/src/test/java/com/ankurm/interviewlab/quicksort/LegacyTest.java b/quick-sort/src/test/java/com/ankurm/interviewlab/quicksort/LegacyTest.java new file mode 100644 index 0000000..9e6b5af --- /dev/null +++ b/quick-sort/src/test/java/com/ankurm/interviewlab/quicksort/LegacyTest.java @@ -0,0 +1,124 @@ +package com.ankurm.interviewlab.quicksort; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import com.ankurm.interviewlab.quicksort.legacy.FirstPivotQuickSort; +import com.ankurm.interviewlab.quicksort.legacy.LomutoQuickSort2015; +import com.ankurm.interviewlab.quicksort.legacy.TempArrayQuickSort; +import com.ankurm.interviewlab.quicksort.support.Transcript; +import java.util.Arrays; +import java.util.Random; +import org.junit.jupiter.api.Test; + +/** What the three 2015 programs really do, including the two bugs the old posts never mentioned. */ +class LegacyTest { + + @Test + void tempArrayVersionCorruptsArraysThatContainDuplicates() { + Transcript t = Transcript.start("04-legacy-temp-array.txt", "The 2015 temp-array version (post 2559): fine on distinct keys, corrupts duplicates"); + int[] ok = {15, 32, 45, 25, 34, 29, 14}; + new TempArrayQuickSort(ok).sort(); + assertArrayEquals(new int[] {14, 15, 25, 29, 32, 34, 45}, ok); + t.line("distinct keys [15, 32, 45, 25, 34, 29, 14] -> " + Arrays.toString(ok) + " (correct)").blank(); + + int[] dup = {3, 1, 3, 2}; + new TempArrayQuickSort(dup).sort(); + assertFalse(Arrays.equals(new int[] {1, 2, 3, 3}, dup)); + t.line("duplicates [3, 1, 3, 2] -> " + Arrays.toString(dup) + " (expected [1, 2, 3, 3])"); + t.line(" the second 3 was never copied into temp[]; the leftover slot kept its initial 0.").blank(); + + Random r = new Random(2015); + int arrays = 10_000; + int withDup = 0; + int wrong = 0; + for (int k = 0; k < arrays; k++) { + int n = 2 + r.nextInt(7); + int[] a = new int[n]; + for (int i = 0; i < n; i++) { + a[i] = 1 + r.nextInt(9); + } + boolean hasDup = Arrays.stream(a).distinct().count() < n; + int[] expected = a.clone(); + Arrays.sort(expected); + new TempArrayQuickSort(a).sort(); + if (hasDup) { + withDup++; + } + if (!Arrays.equals(expected, a)) { + wrong++; + assertTrue(hasDup, "a wrong answer on an array with distinct keys would be a different bug"); + } + } + assertTrue(wrong > 0); + t.line(String.format("%,d seeded random arrays (length 2..8, keys 1..9): %,d contained a duplicate; %,d came back wrong.", arrays, withDup, wrong)); + t.line("every wrong answer was an array with a duplicate; no array of distinct keys came back wrong."); + t.flush(); + } + + @Test + void firstPivotVersionThrowsWhenThePivotIsTheLargestKeyAtTheEndOfTheArray() { + Transcript t = Transcript.start("05-legacy-first-pivot.txt", "The 2015 first-pivot version (post 2530): the loop condition reads x[i] before checking i <= r"); + int[] nine = {15, 48, 66, 12, 48, 74, 12, 24, 56}; + FirstPivotQuickSort.sort(nine, 0, nine.length - 1); + assertArrayEquals(new int[] {12, 12, 15, 24, 48, 48, 56, 66, 74}, nine); + t.line("the 2015 sample [15, 48, 66, 12, 48, 74, 12, 24, 56] -> " + Arrays.toString(nine) + " (correct)").blank(); + + int[] three = {3, 1, 2}; + ArrayIndexOutOfBoundsException e = assertThrows(ArrayIndexOutOfBoundsException.class, + () -> FirstPivotQuickSort.sort(three.clone(), 0, 2)); + t.line("input [3, 1, 2]: " + e.getClass().getSimpleName() + ": " + e.getMessage()); + int[] fixed = {3, 1, 2}; + FirstPivotQuickSort.sortFixed(fixed, 0, 2); + assertArrayEquals(new int[] {1, 2, 3}, fixed); + t.line("same input, operands of the && swapped: " + Arrays.toString(fixed)).blank(); + + Random r = new Random(2015); + int arrays = 10_000; + int threw = 0; + int fixedWrong = 0; + for (int k = 0; k < arrays; k++) { + int n = 1 + r.nextInt(8); + int[] a = new int[n]; + for (int i = 0; i < n; i++) { + a[i] = r.nextInt(20); + } + int[] expected = a.clone(); + Arrays.sort(expected); + try { + FirstPivotQuickSort.sort(a.clone(), 0, n - 1); + } catch (ArrayIndexOutOfBoundsException ex) { + threw++; + } + int[] f = a.clone(); + FirstPivotQuickSort.sortFixed(f, 0, n - 1); + if (!Arrays.equals(expected, f)) { + fixedWrong++; + } + } + assertTrue(threw > 0); + assertEquals(0, fixedWrong); + t.line(String.format("%,d seeded random arrays (length 1..8, keys 0..19): original threw on %,d; fixed version wrong on %d.", arrays, threw, fixedWrong)); + t.flush(); + } + + @Test + void lomutoFrom2531IsTheSameAlgorithmAsTheCleanLomuto() { + Random r = new Random(2531); + for (int k = 0; k < 5_000; k++) { + int n = r.nextInt(30); + int[] a = new int[n]; + for (int i = 0; i < n; i++) { + a[i] = r.nextInt(15); + } + int[] x = a.clone(); + int[] y = a.clone(); + LomutoQuickSort2015.sort(x); + Lomuto.sort(y); + assertArrayEquals(y, x); + } + } +} diff --git a/quick-sort/src/test/java/com/ankurm/interviewlab/quicksort/PitfallsTest.java b/quick-sort/src/test/java/com/ankurm/interviewlab/quicksort/PitfallsTest.java new file mode 100644 index 0000000..2ba31e9 --- /dev/null +++ b/quick-sort/src/test/java/com/ankurm/interviewlab/quicksort/PitfallsTest.java @@ -0,0 +1,68 @@ +package com.ankurm.interviewlab.quicksort; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; + +import com.ankurm.interviewlab.quicksort.support.Data; +import com.ankurm.interviewlab.quicksort.support.Transcript; +import java.util.Arrays; +import org.junit.jupiter.api.Test; + +class PitfallsTest { + + @Test + void hoareMistakesThatLookFine() { + Transcript t = Transcript.start("12-pitfalls.txt", "Hoare mistakes that look reasonable"); + + int[] two = {1, 2}; + Throwable thrown = Data.runWithStack(256 * 1024, () -> Pitfalls.hoareLastPivotLeftIncludesP(two, 0, 1)); + assertInstanceOf(StackOverflowError.class, thrown); + t.line("1. last element as pivot with Hoare's (lo,p) / (p+1,hi) recursion, input [1, 2]:"); + t.line(" " + thrown.getClass().getSimpleName() + " (the partition returns p = 1 = hi, so (lo, p) is the same range again)").blank(); + + int[] in = {2, 3, 1}; + int[] a = in.clone(); + Pitfalls.hoareTreatsPAsPivotSlot(a, 0, in.length - 1); + int[] expected = in.clone(); + Arrays.sort(expected); + assertFalse(Arrays.equals(expected, a)); + t.line("2. Hoare partition, but recursing on (lo, p-1) and (p+1, hi) as Lomuto does, input " + Arrays.toString(in) + ":"); + t.line(" result " + Arrays.toString(a) + " (expected " + Arrays.toString(expected) + ")").blank(); + + for (int n = 3; n <= 5; n++) { + int[] wrongAndTotal = new int[2]; + permutations(new int[n], new boolean[n], 0, wrongAndTotal); + t.line(" all " + wrongAndTotal[1] + " permutations of 1.." + n + ": " + wrongAndTotal[0] + " come back unsorted"); + } + t.blank(); + + int[] ok = in.clone(); + Hoare.sort(ok); + assertArrayEquals(expected, ok); + t.line("the real Hoare.sort on the same input: " + Arrays.toString(ok)); + t.flush(); + } + + private static void permutations(int[] a, boolean[] used, int k, int[] wrongAndTotal) { + if (k == a.length) { + int[] copy = a.clone(); + Pitfalls.hoareTreatsPAsPivotSlot(copy, 0, copy.length - 1); + int[] expected = a.clone(); + Arrays.sort(expected); + wrongAndTotal[1]++; + if (!Arrays.equals(expected, copy)) { + wrongAndTotal[0]++; + } + return; + } + for (int v = 1; v <= a.length; v++) { + if (!used[v - 1]) { + used[v - 1] = true; + a[k] = v; + permutations(a, used, k + 1, wrongAndTotal); + used[v - 1] = false; + } + } + } +} diff --git a/quick-sort/src/test/java/com/ankurm/interviewlab/quicksort/SingleFileTest.java b/quick-sort/src/test/java/com/ankurm/interviewlab/quicksort/SingleFileTest.java new file mode 100644 index 0000000..a44c772 --- /dev/null +++ b/quick-sort/src/test/java/com/ankurm/interviewlab/quicksort/SingleFileTest.java @@ -0,0 +1,49 @@ +package com.ankurm.interviewlab.quicksort; + +import static org.junit.jupiter.api.Assertions.assertTrue; + +import com.ankurm.interviewlab.quicksort.support.Transcript; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.List; +import org.junit.jupiter.api.Test; + +/** Runs download/QuickSort.java exactly the way a reader would (java QuickSort.java), feeding the 2015 sample inputs. */ +class SingleFileTest { + + private static List run(String stdin) throws IOException, InterruptedException { + String java = Path.of(System.getProperty("java.home"), "bin", "java").toString(); + Process p = new ProcessBuilder(java, "download/QuickSort.java") + .redirectError(ProcessBuilder.Redirect.DISCARD) + .start(); + p.getOutputStream().write(stdin.getBytes(StandardCharsets.UTF_8)); + p.getOutputStream().close(); + String out = new String(p.getInputStream().readAllBytes(), StandardCharsets.UTF_8); + assertTrue(p.waitFor() == 0, "program exited non-zero"); + return new ArrayList<>(List.of(out.split("\n"))); + } + + @Test + void sampleSessions() throws Exception { + Transcript t = Transcript.start("14-single-file-sessions.txt", "java download/QuickSort.java, with the sample inputs of the three 2015 posts"); + String[][] sessions = { + {"7 elements (post 2559)", "7\n15\n32\n45\n25\n34\n29\n14\n", "14 15 25 29 32 34 45"}, + {"9 elements with duplicates (post 2530)", "9\n15\n48\n66\n12\n48\n74\n12\n24\n56\n", "12 12 15 24 48 48 56 66 74"}, + {"6 elements (post 2531)", "6\n15\n34\n26\n67\n95\n24\n", "15 24 26 34 67 95"}, + }; + for (String[] s : sessions) { + List out = run(s[1]); + t.line("session: " + s[0]); + String expected = "[" + s[2].replace(" ", ", ") + "]"; + for (String prefix : new String[] {"Lomuto:", "Hoare:", "Randomized:"}) { + String line = out.stream().filter(l -> l.startsWith(prefix)).findFirst().orElseThrow(); + assertTrue(line.endsWith(expected), line); + } + out.forEach(l -> t.line(" " + l)); + t.blank(); + } + t.flush(); + } +} diff --git a/quick-sort/src/test/java/com/ankurm/interviewlab/quicksort/StackTest.java b/quick-sort/src/test/java/com/ankurm/interviewlab/quicksort/StackTest.java new file mode 100644 index 0000000..222a18b --- /dev/null +++ b/quick-sort/src/test/java/com/ankurm/interviewlab/quicksort/StackTest.java @@ -0,0 +1,52 @@ +package com.ankurm.interviewlab.quicksort; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import com.ankurm.interviewlab.quicksort.support.Data; +import com.ankurm.interviewlab.quicksort.support.Transcript; +import java.util.Arrays; +import java.util.Locale; +import org.junit.jupiter.api.Test; + +/** Worst-case input does not just cost time, it can kill the thread: recursion depth is the other half of "O(n^2)". */ +class StackTest { + static final long STACK = 256 * 1024; // a deliberately small thread stack so the failure is quick and repeatable + + @Test + void sortedInputOverflowsTheStackUnlessWeRecurseIntoTheSmallerSide() { + int n = 100_000; + Transcript t = Transcript.start("10-stack-depth.txt", "Sorted input, n = " + String.format(Locale.ROOT, "%,d", n) + ", on a thread with a " + STACK / 1024 + " KB stack"); + + int[] plain = Data.sorted(n); + Throwable plainResult = Data.runWithStack(STACK, () -> Lomuto.sort(plain)); + assertInstanceOf(StackOverflowError.class, plainResult); + t.line("Lomuto.sort (recurse into both sides): " + plainResult.getClass().getSimpleName()); + + int[] safe = Data.sorted(n); + int[] depth = new int[1]; + Throwable safeResult = Data.runWithStack(STACK, () -> depth[0] = StackSafe.sort(safe)); + assertNull(safeResult); + assertArrayEquals(Data.sorted(n), safe); + t.line("StackSafe.sort (smaller side first): sorted, deepest recursion = " + depth[0]); + t.line("log2(" + n + ") = " + String.format(Locale.ROOT, "%.1f", Math.log(n) / Math.log(2))); + t.blank().line("The depth at which a StackOverflowError appears depends on the JVM, the JIT state and -Xss;"); + t.line("what is stable is that plain recursion needs ~n frames here and StackSafe needs at most about log2(n)."); + t.flush(); + assertTrue(depth[0] <= 18, "depth " + depth[0]); + } + + @Test + void stackSafeSortsEveryShapeOfInput() { + int n = 20_000; + for (int[] in : new int[][] {Data.random(n, 1), Data.sorted(n), Data.reversed(n), Data.allEqual(n), Data.fewUnique(n, 1)}) { + int[] expected = in.clone(); + Arrays.sort(expected); + int[] a = in.clone(); + StackSafe.sort(a); + assertArrayEquals(expected, a); + } + } +} diff --git a/quick-sort/src/test/java/com/ankurm/interviewlab/quicksort/support/Data.java b/quick-sort/src/test/java/com/ankurm/interviewlab/quicksort/support/Data.java new file mode 100644 index 0000000..c0fe425 --- /dev/null +++ b/quick-sort/src/test/java/com/ankurm/interviewlab/quicksort/support/Data.java @@ -0,0 +1,68 @@ +package com.ankurm.interviewlab.quicksort.support; + +import java.util.Random; + +/** Seeded, reproducible inputs. */ +public final class Data { + private Data() {} + + public static int[] random(int n, long seed) { + Random r = new Random(seed); + int[] a = new int[n]; + for (int i = 0; i < n; i++) { + a[i] = r.nextInt(1_000_000); + } + return a; + } + + public static int[] sorted(int n) { + int[] a = new int[n]; + for (int i = 0; i < n; i++) { + a[i] = i; + } + return a; + } + + public static int[] reversed(int n) { + int[] a = new int[n]; + for (int i = 0; i < n; i++) { + a[i] = n - i; + } + return a; + } + + public static int[] allEqual(int n) { + int[] a = new int[n]; + java.util.Arrays.fill(a, 7); + return a; + } + + /** n values drawn from only 10 distinct keys. */ + public static int[] fewUnique(int n, long seed) { + Random r = new Random(seed); + int[] a = new int[n]; + for (int i = 0; i < n; i++) { + a[i] = r.nextInt(10); + } + return a; + } + + /** Runs the task on a thread with the given stack size; returns the Throwable it ended with, or null. */ + public static Throwable runWithStack(long stackBytes, Runnable task) { + Throwable[] result = new Throwable[1]; + Thread t = new Thread(null, () -> { + try { + task.run(); + } catch (Throwable e) { + result[0] = e; + } + }, "small-stack", stackBytes); + t.start(); + try { + t.join(); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + return result[0]; + } +} diff --git a/quick-sort/src/test/java/com/ankurm/interviewlab/quicksort/support/Transcript.java b/quick-sort/src/test/java/com/ankurm/interviewlab/quicksort/support/Transcript.java new file mode 100644 index 0000000..a269433 --- /dev/null +++ b/quick-sort/src/test/java/com/ankurm/interviewlab/quicksort/support/Transcript.java @@ -0,0 +1,43 @@ +package com.ankurm.interviewlab.quicksort.support; + +import java.io.IOException; +import java.io.UncheckedIOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.List; + +/** Writes output/NN-*.txt while the calling test asserts the same numbers it prints. */ +public final class Transcript { + private final Path path; + private final List lines = new ArrayList<>(); + + private Transcript(Path path, String header) { + this.path = path; + lines.add(header); + lines.add("=".repeat(Math.min(header.length(), 100))); + lines.add(""); + } + + public static Transcript start(String fileName, String header) { + Path dir = Path.of("output"); + try { + Files.createDirectories(dir); + } catch (IOException e) { + throw new UncheckedIOException(e); + } + return new Transcript(dir.resolve(fileName), header); + } + + public Transcript line(String text) { lines.add(text); return this; } + public Transcript blank() { lines.add(""); return this; } + + public void flush() { + try { + Files.write(path, (String.join("\n", lines) + "\n").getBytes(StandardCharsets.UTF_8)); + } catch (IOException e) { + throw new UncheckedIOException(e); + } + } +}