Add merge-sort module: top-down and bottom-up merge sort, dry runs, stability, comparison counts against the exact worst case, linked lists, counting inversions, quick sort and TimSort comparisons, and the 2015 program re-run (unstable on ties, quadratic allocation) (17 tests, 15 transcripts)

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_017ic4b6vDJ5fWY5uEZaJFNi
This commit is contained in:
Claude
2026-12-03 23:34:17 +05:30
parent 5419e5057d
commit 5ed8dca130
42 changed files with 1710 additions and 0 deletions
+1
View File
@@ -35,6 +35,7 @@ One module per article. This repository currently holds:
| [`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 |
| [`bst`](bst/) | Binary Search Tree in Java: Insert, Delete, Search, Validate BST and LCA (With Dry Runs) | this commit |
| [`merge-sort`](merge-sort/) | Merge Sort in Java: Recursive and Bottom-Up, Dry Run, Complexity and Counting Inversions | this commit |
## `collections` module
+74
View File
@@ -0,0 +1,74 @@
# merge-sort
Companion code for the ankurm.com article **[Merge Sort in Java: Recursive and Bottom-Up, Dry Run, Complexity and Counting Inversions](https://ankurm.com/implementing-merge-sort-algorithm-in-java/)**
(an in-place rewrite of the 2015 post "Implementing Merge Sort Algorithm in Java").
Top-down and bottom-up merge sort, dry runs, the one character that decides stability, comparison counts against the exact worst-case formula,
merge sort on linked lists, counting inversions, a comparison with quick sort and `Arrays.sort`, and the 2015 program run again: it sorts correctly,
but is not stable on ties and allocates a full-size array in every merge (6,400 MB for 40,000 ints). Every figure and console line in the article is
quoted from a file in `output/`, which the JUnit tests write while asserting the numbers. There is no `docs/` folder: the explanations live in the article.
## Versions
| Component | Version | Verified against |
|---|---|---|
| JDK | Temurin 25.0.5.1+2 (LTS) | `java -version` |
| JUnit | 6.1.3 | `junit-bom` on Maven Central |
| Maven | 3.9.x | `mvn -version` |
## Quickstart
```bash
cd merge-sort
export JAVA_HOME=/path/to/jdk-25 PATH="$JAVA_HOME/bin:$PATH"
./scripts/run-all.sh # runs 17 tests and regenerates output/*.txt
java download/MergeSort.java # the single-file program from the article (type the numbers in)
java legacy/MergeSort.java # the original 2015 program, unchanged
```
The first Maven run must be online so the plugins land in the local cache.
## Source layout
```
merge-sort/
├── pom.xml
├── scripts/run-all.sh
├── download/MergeSort.java single-file program, also attached to the article
├── legacy/MergeSort.java the 2015 program, unchanged
├── src/main/java/com/ankurm/interviewlab/mergesort/
│ ├── TopDown.java recursive merge sort, one shared buffer
│ ├── BottomUp.java iterative: runs of width 1, 2, 4, ...
│ ├── SkipSorted.java skips merges whose runs are already in order
│ ├── ListMergeSort.java singly linked list, top-down and bottom-up
│ ├── BrokenSplit.java the wrong linked-list split, on purpose
│ ├── Inversions.java O(n log n) count plus the O(n^2) definition
│ ├── Stability.java generic version with the tie rule as a switch
│ ├── DryRun.java records every merge
│ ├── Measured.java counts comparisons (also a randomized quick sort)
│ └── legacy/Original2015.java the 2015 methods in a package, for tests
├── src/test/java/.../ tests that write output/
└── output/*.txt captured real output
```
## Captured output (`output/`)
| File | What it shows |
|---|---|
| `01-dry-run-top-down.txt` | the six merges on `[38, 27, 43, 3, 9, 82, 10]` |
| `02-dry-run-final-merge.txt` | the last merge, element by element |
| `03-dry-run-bottom-up.txt` | the same array, pass by pass |
| `04-stability.txt` | `<=` vs `<` on records with equal keys |
| `05-original-2015-program.txt` | the 2015 program with its sample input |
| `06-original-allocation.txt` | `new int[arr.length]` per merge, measured |
| `07-comparison-counts.txt` | comparisons on random, sorted, reversed and worst-case input |
| `08-brute-force.txt` | 488,281 exhaustive + 20,000 random arrays, 0 disagreements |
| `09-linked-list.txt` | relinking nodes, 1,000,000 nodes, the broken split |
| `10-inversions.txt` | inversion counts, `int` overflow, the wrong tie rule |
| `11-merge-vs-quick.txt` | comparisons against randomized quick sort |
| `12-jdk-arrays-sort.txt` | what `Arrays.sort` calls, read from `lib/src.zip` |
| `13-midpoint.txt` | `(lo + hi) / 2` overflow |
| `14-timsort-comparisons.txt` | comparisons of `Arrays.sort(Integer[], c)` on ordered input |
| `15-single-file-sessions.txt` | the single-file program with typed input |
Comparison counts are deterministic. Allocated-byte figures in `06` can move by a fraction of a percent between JVM builds.
+77
View File
@@ -0,0 +1,77 @@
import java.util.Arrays;
import java.util.Scanner;
/**
* Merge Sort in Java, single file: top-down, bottom-up and inversion count.
*
* javac MergeSort.java && java MergeSort
* (or, JDK 11+: java MergeSort.java)
*
* From ankurm.com: https://ankurm.com/implementing-merge-sort-algorithm-in-java/
*/
public class MergeSort {
// ---- top-down: split, sort both halves, merge ---------------------------------------------
static long sort(int[] a, int[] buf, int lo, int hi) {
if (lo >= hi) {
return 0; // 0 or 1 element: already sorted
}
int mid = lo + (hi - lo) / 2;
long inversions = sort(a, buf, lo, mid) + sort(a, buf, mid + 1, hi);
return inversions + merge(a, buf, lo, mid, hi);
}
// ---- merge a[lo..mid] with a[mid+1..hi]; returns the inversions between the two runs -------
static long merge(int[] a, int[] buf, int lo, int mid, int hi) {
System.arraycopy(a, lo, buf, lo, hi - lo + 1);
long inversions = 0;
int i = lo;
int j = mid + 1;
for (int k = lo; k <= hi; k++) {
if (i > mid) {
a[k] = buf[j++];
} else if (j > hi) {
a[k] = buf[i++];
} else if (buf[j] < buf[i]) {
inversions += mid - i + 1;
a[k] = buf[j++];
} else {
a[k] = buf[i++]; // ties go left: stable
}
}
return inversions;
}
// ---- bottom-up: no recursion ---------------------------------------------------------------
static void sortBottomUp(int[] a) {
int n = a.length;
int[] buf = new int[n];
for (int width = 1; width < n; width *= 2) {
for (int lo = 0; lo < n - width; lo += 2 * width) {
merge(a, buf, lo, lo + width - 1, Math.min(lo + 2 * width - 1, n - 1));
}
}
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Number of elements: ");
int n = in.nextInt();
int[] input = new int[n];
System.out.print("Elements: ");
for (int i = 0; i < n; i++) {
input[i] = in.nextInt();
}
System.out.println();
int[] topDown = input.clone();
long inversions = sort(topDown, new int[n], 0, n - 1);
int[] bottomUp = input.clone();
sortBottomUp(bottomUp);
System.out.println("Input: " + Arrays.toString(input));
System.out.println("Top-down: " + Arrays.toString(topDown));
System.out.println("Bottom-up: " + Arrays.toString(bottomUp));
System.out.println("Inversions: " + inversions);
}
}
+89
View File
@@ -0,0 +1,89 @@
import java.io.*;
class MergeSort {
/**
* Merges two adjacent sorted sub-arrays of arr[] into a single sorted section.
*
* @param arr the array containing both sub-arrays
* @param leftStart starting index of the left sub-array
* @param rightStart starting index of the right sub-array
* @param rightEnd ending index (inclusive) of the right sub-array
*/
static void merge(int[] arr, int leftStart, int rightStart, int rightEnd) {
int[] tempArray = new int[arr.length]; // temporary buffer for merged output
int leftPointer = leftStart; // pointer into the left sub-array
int rightPointer = rightStart; // pointer into the right sub-array
int tempIndex = -1; // current write position in tempArray
// Compare elements from both halves and place the smaller one into tempArray
while (leftPointer <= rightStart - 1 && rightPointer <= rightEnd) {
if (arr[leftPointer] < arr[rightPointer]) {
tempIndex++;
tempArray[tempIndex] = arr[leftPointer];
leftPointer++;
} else {
tempIndex++;
tempArray[tempIndex] = arr[rightPointer];
rightPointer++;
}
}
// Copy any remaining elements from the left half
if (leftPointer > rightStart - 1) {
for (int i = rightPointer; i <= rightEnd; i++) {
tempIndex++;
tempArray[tempIndex] = arr[i];
}
} else {
// Copy any remaining elements from the right half
for (int i = leftPointer; i <= rightStart - 1; i++) {
tempIndex++;
tempArray[tempIndex] = arr[i];
}
}
// Copy the merged result back into the original array
for (int i = 0; i <= tempIndex; i++) {
arr[leftStart + i] = tempArray[i];
}
}
/**
* Recursively sorts arr[leftIndex..rightIndex] using the merge sort algorithm.
*
* @param arr the array to sort
* @param leftIndex starting index of the portion to sort
* @param rightIndex ending index (inclusive) of the portion to sort
*/
static void mergeSort(int[] arr, int leftIndex, int rightIndex) {
if (leftIndex < rightIndex) {
int midIndex = (leftIndex + rightIndex) / 2;
mergeSort(arr, leftIndex, midIndex); // sort the left half
mergeSort(arr, midIndex + 1, rightIndex); // sort the right half
merge(arr, leftIndex, midIndex + 1, rightIndex); // merge both halves
}
}
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the number of elements:");
int elementCount = Integer.parseInt(reader.readLine());
int[] arr = new int[elementCount];
for (int i = 0; i < elementCount; i++) {
System.out.println("Enter element " + (i + 1) + ":");
arr[i] = Integer.parseInt(reader.readLine());
}
mergeSort(arr, 0, elementCount - 1);
System.out.println("Sorted array:");
for (int i = 0; i < elementCount; i++) {
System.out.println(arr[i]);
}
}
}
+17
View File
@@ -0,0 +1,17 @@
Top-down merge sort on [38, 27, 43, 3, 9, 82, 10]: merges in execution order
============================================================================
1. a[0..1] [38] + [27] -> [27, 38] 1 comparisons
array now [27, 38, 43, 3, 9, 82, 10]
2. a[2..3] [43] + [3] -> [3, 43] 1 comparisons
array now [27, 38, 3, 43, 9, 82, 10]
3. a[0..3] [27, 38] + [3, 43] -> [3, 27, 38, 43] 3 comparisons
array now [3, 27, 38, 43, 9, 82, 10]
4. a[4..5] [9] + [82] -> [9, 82] 1 comparisons
array now [3, 27, 38, 43, 9, 82, 10]
5. a[4..6] [9, 82] + [10] -> [9, 10, 82] 2 comparisons
array now [3, 27, 38, 43, 9, 10, 82]
6. a[0..6] [3, 27, 38, 43] + [9, 10, 82] -> [3, 9, 10, 27, 38, 43, 82] 6 comparisons
array now [3, 9, 10, 27, 38, 43, 82]
total: 6 merges, 14 comparisons
@@ -0,0 +1,10 @@
The last merge, element by element: [3, 27, 38, 43] + [9, 10, 82]
=================================================================
k=0 3 <= 9, take left 3 output [3]
k=1 9 < 27, take right 9 output [3, 9]
k=2 10 < 27, take right 10 output [3, 9, 10]
k=3 27 <= 82, take left 27 output [3, 9, 10, 27]
k=4 38 <= 82, take left 38 output [3, 9, 10, 27, 38]
k=5 43 <= 82, take left 43 output [3, 9, 10, 27, 38, 43]
k=6 left run empty, copy 82 output [3, 9, 10, 27, 38, 43, 82]
@@ -0,0 +1,17 @@
Bottom-up merge sort on [38, 27, 43, 3, 9, 82, 10]: one block per pass
======================================================================
pass with width 1:
[38] + [27] -> [27, 38]
[43] + [3] -> [3, 43]
[9] + [82] -> [9, 82]
array after the pass [27, 38, 3, 43, 9, 82, 10]
pass with width 2:
[27, 38] + [3, 43] -> [3, 27, 38, 43]
[9, 82] + [10] -> [9, 10, 82]
array after the pass [3, 27, 38, 43, 9, 10, 82]
pass with width 4:
[3, 27, 38, 43] + [9, 10, 82] -> [3, 9, 10, 27, 38, 43, 82]
array after the pass [3, 9, 10, 27, 38, 43, 82]
total comparisons: 14
+7
View File
@@ -0,0 +1,7 @@
Sorting students by marks only: equal marks should keep their input order
=========================================================================
input [Asha:82, Bala:75, Chitra:82, Dev:75, Esha:90]
ties take LEFT (cmp <= 0) [Bala:75, Dev:75, Asha:82, Chitra:82, Esha:90]
Arrays.sort(T[], Comparator) [Bala:75, Dev:75, Asha:82, Chitra:82, Esha:90]
ties take RIGHT (cmp < 0) [Dev:75, Bala:75, Chitra:82, Asha:82, Esha:90] <- the 2015 rule: not stable
@@ -0,0 +1,15 @@
java legacy/MergeSort.java, typing 5, 38, 27, 43, 3, 9 (the sample of the 2015 article)
=======================================================================================
Enter the number of elements:
Enter element 1:
Enter element 2:
Enter element 3:
Enter element 4:
Enter element 5:
Sorted array:
3
9
27
38
43
@@ -0,0 +1,9 @@
new int[arr.length] inside merge(): elements allocated, and bytes measured with ThreadMXBean (MB = 1,000,000 bytes)
====================================================================================================
10,000 seeded random arrays sorted by the 2015 methods vs Arrays.sort: 0 disagreements.
n merges int slots allocated 2015 measured one shared buffer
1,000 999 999,000 4.0 MB 0.01 MB
10,000 9,999 99,990,000 400.1 MB 0.04 MB
40,000 39,999 1,599,960,000 6,400.5 MB 0.16 MB
@@ -0,0 +1,20 @@
Element comparisons. random = new Random(7).nextInt(); worst = built by Data.worstCase
======================================================================================
n input top-down bottom-up skip-sorted worst bound
1,000 random 8,742 8,734 9,437 8,977
1,000 sorted 5,044 5,052 999 8,977
1,000 reversed 4,932 4,932 5,931 8,977
1,000 worst 8,977 8,976 9,976 8,977
1,024 random 8,963 8,963 9,634 9,217
1,024 sorted 5,120 5,120 1,023 9,217
1,024 reversed 5,120 5,120 6,143 9,217
1,024 worst 9,217 9,217 10,240 9,217
100,000 random 1,536,818 1,566,951 1,596,193 1,568,929
100,000 sorted 853,904 877,968 99,999 1,568,929
100,000 reversed 815,024 815,024 915,023 1,568,929
100,000 worst 1,568,929 1,585,582 1,668,928 1,568,929
1,048,576 random 19,646,187 19,646,187 20,337,833 19,922,945
1,048,576 sorted 10,485,760 10,485,760 1,048,575 19,922,945
1,048,576 reversed 10,485,760 10,485,760 11,534,335 19,922,945
1,048,576 worst 19,922,945 19,922,945 20,971,520 19,922,945
+9
View File
@@ -0,0 +1,9 @@
Cross-checks against Arrays.sort and the O(n^2) inversion definition
====================================================================
every array of length 0..8 over 5 values: 488,281 arrays
random arrays, length 0..199 (seed 2026): 20,000 arrays
each checked: top-down, bottom-up, skip-sorted, linked list (top-down), linked list (bottom-up), inversion count
disagreements: 0
stability, records with 5 distinct keys: 5,000 arrays, same object order as Arrays.sort(T[], Comparator): 0 disagreements
+11
View File
@@ -0,0 +1,11 @@
Merge sort on a singly linked list
==================================
before 38 -> 27 -> 43 -> 3 -> 9 -> 82 -> 10 -> null
after 3 -> 9 -> 10 -> 27 -> 38 -> 43 -> 82 -> null
same 7 node objects, relinked: true
1,000,000 random values: top-down and bottom-up both match Arrays.sort
split written with fast = head (instead of head.next), input 2 -> 1 -> null:
java.lang.StackOverflowError
+13
View File
@@ -0,0 +1,13 @@
Counting inversions
===================
[2, 4, 1, 3, 5] 3
[38, 27, 43, 3, 9, 82, 10] 11
[1, 2, 3, 4, 5] 0
[5, 4, 3, 2, 1] 10
reversed array, n = 100,000: 4,999,950,000 (Integer.MAX_VALUE = 2,147,483,647)
the same total kept in an int: 704,982,704
[7, 7, 7, 7] ties take left : 0
[7, 7, 7, 7] ties take right: 6 (wrong: equal values are not an inversion)
+8
View File
@@ -0,0 +1,8 @@
Comparisons: top-down merge sort vs randomized Lomuto quick sort (pivot seed 1)
===============================================================================
n input merge sort quick sort
1,000 random 8,742 10,900
10,000 random 120,548 156,821
100,000 random 1,536,818 2,046,983
20,000 10 distinct keys 253,189 20,103,072
+22
View File
@@ -0,0 +1,22 @@
From lib/src.zip of Java 25.0.5.1
=================================
Arrays.java, line 98:
public static void sort(int[] a) {
DualPivotQuicksort.sort(a, 0, 0, a.length);
}
Arrays.java, line 1034:
public static void sort(Object[] a) {
if (LegacyMergeSort.userRequested)
legacyMergeSort(a);
else
ComparableTimSort.sort(a, 0, a.length, null, 0, 0);
}
Arrays.java, line 989:
Boolean.getBoolean("java.util.Arrays.useLegacyMergeSort");
TimSort.java, line 80:
private static final int MIN_MERGE = 32;
+7
View File
@@ -0,0 +1,7 @@
The midpoint, with indices near the top of the int range (arithmetic only, no array allocated)
==============================================================================================
lo = 1,200,000,000 hi = 1,500,000,000
(lo + hi) / 2 = -797,483,648
lo + (hi - lo) / 2 = 1,350,000,000
(lo + hi) >>> 1 = 1,350,000,000
@@ -0,0 +1,9 @@
Comparisons for n = 100,000: our merge sort vs Arrays.sort(Integer[], countingComparator)
=========================================================================================
input top-down skip-sorted Arrays.sort
random 1,536,818 1,596,193 1,534,762
sorted 853,904 99,999 99,999
reversed 815,024 915,023 99,999
4 sorted runs 953,895 299,990 299,994
sorted, 10 swaps 1,017,088 487,083 101,078
@@ -0,0 +1,17 @@
java download/MergeSort.java, with two inputs typed in
======================================================
typed: 5 38 27 43 3 9
Number of elements: Elements:
Input: [38, 27, 43, 3, 9]
Top-down: [3, 9, 27, 38, 43]
Bottom-up: [3, 9, 27, 38, 43]
Inversions: 7
typed: 7 38 27 43 3 9 82 10
Number of elements: Elements:
Input: [38, 27, 43, 3, 9, 82, 10]
Top-down: [3, 9, 10, 27, 38, 43, 82]
Bottom-up: [3, 9, 10, 27, 38, 43, 82]
Inversions: 11
+63
View File
@@ -0,0 +1,63 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.ankurm.interviewlab</groupId>
<artifactId>merge-sort</artifactId>
<version>1.0.0</version>
<packaging>jar</packaging>
<name>java-interview-lab :: merge-sort</name>
<description>
Runnable companion code for ankurm.com's "Merge Sort in Java" article: top-down and bottom-up merge sort, dry runs, stability, comparison counts, linked lists, counting inversions and the 2015 program it replaces.
</description>
<properties>
<maven.compiler.release>25</maven.compiler.release>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<junit.version>6.1.3</junit.version>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.junit</groupId>
<artifactId>junit-bom</artifactId>
<version>${junit.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-launcher</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.14.0</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.6.0</version>
<configuration>
<argLine>-Xmx512m -Duser.timezone=UTC -Dfile.encoding=UTF-8</argLine>
</configuration>
</plugin>
</plugins>
</build>
</project>
+9
View File
@@ -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
@@ -0,0 +1,19 @@
package com.ankurm.interviewlab.mergesort;
/** Bottom-up merge sort: no recursion. Merge runs of width 1, then 2, 4, 8, ... */
public final class BottomUp {
private BottomUp() {}
public static void sort(int[] a) {
int n = a.length;
int[] buf = new int[n];
for (int width = 1; width < n; width *= 2) {
// a left run needs a non-empty right run beside it, hence lo < n - width
for (int lo = 0; lo < n - width; lo += 2 * width) {
int mid = lo + width - 1;
int hi = Math.min(lo + 2 * width - 1, n - 1); // the last right run may be short
TopDown.merge(a, buf, lo, mid, hi);
}
}
}
}
@@ -0,0 +1,23 @@
package com.ankurm.interviewlab.mergesort;
import com.ankurm.interviewlab.mergesort.ListMergeSort.Node;
/** The classic linked-list mistake, kept so the test can show what it does. Do not copy. */
public final class BrokenSplit {
private BrokenSplit() {}
public static Node sort(Node head) {
if (head == null || head.next == null) {
return head;
}
Node slow = head;
Node fast = head; // WRONG: should be head.next
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
}
Node second = slow.next; // for 2 nodes this is null ...
slow.next = null;
return ListMergeSort.merge(sort(head), sort(second)); // ... and head is still 2 nodes long
}
}
@@ -0,0 +1,91 @@
package com.ankurm.interviewlab.mergesort;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/** Instrumented copies that record every merge. */
public final class DryRun {
private DryRun() {}
public record Merge(int lo, int mid, int hi, String left, String right, String result, int comparisons, String array) {}
public static List<Merge> topDown(int[] a) {
List<Merge> out = new ArrayList<>();
split(a, new int[a.length], 0, a.length - 1, out);
return out;
}
private static void split(int[] a, int[] buf, int lo, int hi, List<Merge> out) {
if (lo >= hi) {
return;
}
int mid = lo + (hi - lo) / 2;
split(a, buf, lo, mid, out);
split(a, buf, mid + 1, hi, out);
out.add(record(a, buf, lo, mid, hi));
}
public static List<List<Merge>> bottomUp(int[] a) {
List<List<Merge>> passes = new ArrayList<>();
int n = a.length;
int[] buf = new int[n];
for (int width = 1; width < n; width *= 2) {
List<Merge> pass = new ArrayList<>();
for (int lo = 0; lo < n - width; lo += 2 * width) {
pass.add(record(a, buf, lo, lo + width - 1, Math.min(lo + 2 * width - 1, n - 1)));
}
passes.add(pass);
}
return passes;
}
private static Merge record(int[] a, int[] buf, int lo, int mid, int hi) {
String left = slice(a, lo, mid);
String right = slice(a, mid + 1, hi);
int i = lo;
int j = mid + 1;
int compared = 0;
while (i <= mid && j <= hi) { // count what merge() is about to compare
compared++;
if (a[j] < a[i]) {
j++;
} else {
i++;
}
}
TopDown.merge(a, buf, lo, mid, hi);
return new Merge(lo, mid, hi, left, right, slice(a, lo, hi), compared, Arrays.toString(a));
}
private static String slice(int[] a, int lo, int hi) {
return Arrays.toString(Arrays.copyOfRange(a, lo, hi + 1));
}
/** One line per element written by a single merge of a[lo..mid] and a[mid+1..hi]. */
public static List<String> mergeSteps(int[] a, int mid) {
List<String> out = new ArrayList<>();
int hi = a.length - 1;
int i = 0;
int j = mid + 1;
int[] result = new int[a.length];
for (int k = 0; k <= hi; k++) {
String why;
if (i > mid) {
why = "left run empty, copy " + a[j];
result[k] = a[j++];
} else if (j > hi) {
why = "right run empty, copy " + a[i];
result[k] = a[i++];
} else if (a[j] < a[i]) {
why = a[j] + " < " + a[i] + ", take right " + a[j];
result[k] = a[j++];
} else {
why = a[i] + " <= " + a[j] + ", take left " + a[i];
result[k] = a[i++];
}
out.add(String.format("k=%d %-30s output %s", k, why, slice(result, 0, k)));
}
return out;
}
}
@@ -0,0 +1,48 @@
package com.ankurm.interviewlab.mergesort;
/** An inversion is a pair i < j with a[i] > a[j]. Merge sort counts them all in O(n log n). */
public final class Inversions {
private Inversions() {}
public static long count(int[] input) {
int[] a = input.clone(); // do not reorder the caller's array
return sortAndCount(a, new int[a.length], 0, a.length - 1);
}
private static long sortAndCount(int[] a, int[] buf, int lo, int hi) {
if (lo >= hi) {
return 0;
}
int mid = lo + (hi - lo) / 2;
long total = sortAndCount(a, buf, lo, mid) + sortAndCount(a, buf, mid + 1, hi);
System.arraycopy(a, lo, buf, lo, hi - lo + 1);
int i = lo;
int j = mid + 1;
for (int k = lo; k <= hi; k++) {
if (i > mid) {
a[k] = buf[j++];
} else if (j > hi) {
a[k] = buf[i++];
} else if (buf[j] < buf[i]) {
total += mid - i + 1; // buf[j] jumps over everything left in the left run
a[k] = buf[j++];
} else {
a[k] = buf[i++];
}
}
return total;
}
/** The O(n^2) definition, used to cross-check. */
public static long bruteForce(int[] a) {
long total = 0;
for (int i = 0; i < a.length; i++) {
for (int j = i + 1; j < a.length; j++) {
if (a[i] > a[j]) {
total++;
}
}
}
return total;
}
}
@@ -0,0 +1,93 @@
package com.ankurm.interviewlab.mergesort;
/** Merge sort on a singly linked list: nodes are relinked, no values are copied. */
public final class ListMergeSort {
private ListMergeSort() {}
public static final class Node {
public final int value;
public Node next;
public Node(int value, Node next) {
this.value = value;
this.next = next;
}
}
/** Top-down: O(n log n) time, O(log n) stack. */
public static Node sort(Node head) {
if (head == null || head.next == null) {
return head;
}
Node slow = head;
Node fast = head.next; // start one ahead, so a 2-node list splits 1 + 1
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
}
Node second = slow.next;
slow.next = null; // cut the list in two
return merge(sort(head), sort(second));
}
public static Node merge(Node a, Node b) {
Node dummy = new Node(0, null);
Node tail = dummy;
while (a != null && b != null) {
if (b.value < a.value) { // ties go to a: stable
tail.next = b;
b = b.next;
} else {
tail.next = a;
a = a.next;
}
tail = tail.next;
}
tail.next = (a != null) ? a : b; // the leftover is attached in one step
return dummy.next;
}
/** Bottom-up: no recursion at all, so O(1) extra space. */
public static Node sortBottomUp(Node head) {
int n = 0;
for (Node p = head; p != null; p = p.next) {
n++;
}
Node dummy = new Node(0, head);
for (int width = 1; width < n; width *= 2) {
Node tail = dummy;
Node cur = dummy.next;
while (cur != null) {
Node left = cur;
Node right = cut(left, width);
cur = cut(right, width);
tail.next = merge(left, right);
while (tail.next != null) {
tail = tail.next;
}
}
}
return dummy.next;
}
/** Detaches the first {@code width} nodes and returns what follows them. */
private static Node cut(Node head, int width) {
for (int i = 1; head != null && i < width; i++) {
head = head.next;
}
if (head == null) {
return null;
}
Node rest = head.next;
head.next = null;
return rest;
}
public static Node of(int... values) {
Node head = null;
for (int i = values.length - 1; i >= 0; i--) {
head = new Node(values[i], head);
}
return head;
}
}
@@ -0,0 +1,93 @@
package com.ankurm.interviewlab.mergesort;
/** Instrumented copies that count element comparisons. */
public final class Measured {
private long comparisons;
public static long topDown(int[] a) {
Measured m = new Measured();
m.split(a, new int[a.length], 0, a.length - 1, false);
return m.comparisons;
}
public static long skipSorted(int[] a) {
Measured m = new Measured();
m.split(a, new int[a.length], 0, a.length - 1, true);
return m.comparisons;
}
public static long bottomUp(int[] a) {
Measured m = new Measured();
int n = a.length;
int[] buf = new int[n];
for (int width = 1; width < n; width *= 2) {
for (int lo = 0; lo < n - width; lo += 2 * width) {
m.merge(a, buf, lo, lo + width - 1, Math.min(lo + 2 * width - 1, n - 1));
}
}
return m.comparisons;
}
/** Randomized quick sort (Lomuto), for the side-by-side table. Same counting rule. */
public static long quick(int[] a, long seed) {
Measured m = new Measured();
m.quick(a, 0, a.length - 1, new java.util.Random(seed));
return m.comparisons;
}
private void split(int[] a, int[] buf, int lo, int hi, boolean skip) {
if (lo >= hi) {
return;
}
int mid = lo + (hi - lo) / 2;
split(a, buf, lo, mid, skip);
split(a, buf, mid + 1, hi, skip);
if (skip) {
comparisons++;
if (a[mid] <= a[mid + 1]) {
return;
}
}
merge(a, buf, lo, mid, hi);
}
private void merge(int[] a, int[] buf, int lo, int mid, int hi) {
System.arraycopy(a, lo, buf, lo, hi - lo + 1);
int i = lo;
int j = mid + 1;
for (int k = lo; k <= hi; k++) {
if (i > mid) {
a[k] = buf[j++];
} else if (j > hi) {
a[k] = buf[i++];
} else {
comparisons++;
a[k] = buf[j] < buf[i] ? buf[j++] : buf[i++];
}
}
}
private void quick(int[] a, int lo, int hi, java.util.Random r) {
if (lo >= hi) {
return;
}
swap(a, lo + r.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) {
swap(a, ++i, j);
}
}
swap(a, i + 1, hi);
quick(a, lo, i, r);
quick(a, i + 2, hi, r);
}
private static void swap(int[] a, int x, int y) {
int t = a[x];
a[x] = a[y];
a[y] = t;
}
}
@@ -0,0 +1,23 @@
package com.ankurm.interviewlab.mergesort;
/** Top-down merge sort that skips the merge when the two runs are already in order. */
public final class SkipSorted {
private SkipSorted() {}
public static void sort(int[] a) {
sort(a, new int[a.length], 0, a.length - 1);
}
private static void sort(int[] a, int[] buf, int lo, int hi) {
if (lo >= hi) {
return;
}
int mid = lo + (hi - lo) / 2;
sort(a, buf, lo, mid);
sort(a, buf, mid + 1, hi);
if (a[mid] <= a[mid + 1]) {
return; // one comparison replaces a whole merge
}
TopDown.merge(a, buf, lo, mid, hi);
}
}
@@ -0,0 +1,36 @@
package com.ankurm.interviewlab.mergesort;
import java.util.Arrays;
import java.util.Comparator;
/** Generic merge sort where the tie rule is a switch, to show what one character does. */
public final class Stability {
private Stability() {}
public static <T> void sort(T[] a, Comparator<? super T> c, boolean tiesTakeLeft) {
sort(a, Arrays.copyOf(a, a.length), 0, a.length - 1, c, tiesTakeLeft);
}
private static <T> void sort(T[] a, T[] buf, int lo, int hi, Comparator<? super T> c, boolean tiesTakeLeft) {
if (lo >= hi) {
return;
}
int mid = lo + (hi - lo) / 2;
sort(a, buf, lo, mid, c, tiesTakeLeft);
sort(a, buf, mid + 1, hi, c, tiesTakeLeft);
System.arraycopy(a, lo, buf, lo, hi - lo + 1);
int i = lo;
int j = mid + 1;
for (int k = lo; k <= hi; k++) {
if (i > mid) {
a[k] = buf[j++];
} else if (j > hi) {
a[k] = buf[i++];
} else {
int cmp = c.compare(buf[i], buf[j]);
boolean takeLeft = tiesTakeLeft ? cmp <= 0 : cmp < 0; // "<" is the 2015 rule
a[k] = takeLeft ? buf[i++] : buf[j++];
}
}
}
}
@@ -0,0 +1,41 @@
package com.ankurm.interviewlab.mergesort;
/** Top-down (recursive) merge sort with one shared buffer. Ranges are inclusive: a[lo..hi]. */
public final class TopDown {
private TopDown() {}
public static void sort(int[] a) {
if (a.length < 2) {
return;
}
sort(a, new int[a.length], 0, a.length - 1); // the only allocation in the whole sort
}
private static void sort(int[] a, int[] buf, int lo, int hi) {
if (lo >= hi) {
return; // 0 or 1 element: already sorted
}
int mid = lo + (hi - lo) / 2; // never overflows, unlike (lo + hi) / 2
sort(a, buf, lo, mid);
sort(a, buf, mid + 1, hi);
merge(a, buf, lo, mid, hi);
}
/** Merges the sorted runs a[lo..mid] and a[mid+1..hi]. */
static void merge(int[] a, int[] buf, int lo, int mid, int hi) {
System.arraycopy(a, lo, buf, lo, hi - lo + 1);
int i = lo; // next unread element of the left run
int j = mid + 1; // next unread element of the right run
for (int k = lo; k <= hi; k++) {
if (i > mid) {
a[k] = buf[j++]; // left run used up
} else if (j > hi) {
a[k] = buf[i++]; // right run used up
} else if (buf[j] < buf[i]) {
a[k] = buf[j++]; // right is STRICTLY smaller
} else {
a[k] = buf[i++]; // ties go to the left: that is stability
}
}
}
}
@@ -0,0 +1,73 @@
package com.ankurm.interviewlab.mergesort.legacy;
/**
* The merge() and mergeSort() methods of the 2015 version of this article, logic and comments unchanged,
* so that tests can call them. The complete original program, with its main method, is legacy/MergeSort.java.
*/
public final class Original2015 {
private Original2015() {}
/**
* Merges two adjacent sorted sub-arrays of arr[] into a single sorted section.
*
* @param arr the array containing both sub-arrays
* @param leftStart starting index of the left sub-array
* @param rightStart starting index of the right sub-array
* @param rightEnd ending index (inclusive) of the right sub-array
*/
public static void merge(int[] arr, int leftStart, int rightStart, int rightEnd) {
int[] tempArray = new int[arr.length]; // temporary buffer for merged output
int leftPointer = leftStart; // pointer into the left sub-array
int rightPointer = rightStart; // pointer into the right sub-array
int tempIndex = -1; // current write position in tempArray
// Compare elements from both halves and place the smaller one into tempArray
while (leftPointer <= rightStart - 1 && rightPointer <= rightEnd) {
if (arr[leftPointer] < arr[rightPointer]) {
tempIndex++;
tempArray[tempIndex] = arr[leftPointer];
leftPointer++;
} else {
tempIndex++;
tempArray[tempIndex] = arr[rightPointer];
rightPointer++;
}
}
// Copy any remaining elements from the left half
if (leftPointer > rightStart - 1) {
for (int i = rightPointer; i <= rightEnd; i++) {
tempIndex++;
tempArray[tempIndex] = arr[i];
}
} else {
// Copy any remaining elements from the right half
for (int i = leftPointer; i <= rightStart - 1; i++) {
tempIndex++;
tempArray[tempIndex] = arr[i];
}
}
// Copy the merged result back into the original array
for (int i = 0; i <= tempIndex; i++) {
arr[leftStart + i] = tempArray[i];
}
}
/**
* Recursively sorts arr[leftIndex..rightIndex] using the merge sort algorithm.
*
* @param arr the array to sort
* @param leftIndex starting index of the portion to sort
* @param rightIndex ending index (inclusive) of the portion to sort
*/
public static void mergeSort(int[] arr, int leftIndex, int rightIndex) {
if (leftIndex < rightIndex) {
int midIndex = (leftIndex + rightIndex) / 2;
mergeSort(arr, leftIndex, midIndex); // sort the left half
mergeSort(arr, midIndex + 1, rightIndex); // sort the right half
merge(arr, leftIndex, midIndex + 1, rightIndex); // merge both halves
}
}
}
@@ -0,0 +1,76 @@
package com.ankurm.interviewlab.mergesort;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import com.ankurm.interviewlab.mergesort.ListMergeSort.Node;
import com.ankurm.interviewlab.mergesort.support.Transcript;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Random;
import org.junit.jupiter.api.Test;
/** Brute-force cross-checks against Arrays.sort and the O(n^2) inversion count. */
class AgreementTest {
static int[] values(Node head, int n) {
int[] out = new int[n];
int i = 0;
for (Node p = head; p != null; p = p.next) out[i++] = p.value;
assertEquals(n, i);
return out;
}
static void check(int[] input) {
int n = input.length;
int[] expected = input.clone();
Arrays.sort(expected);
int[] a = input.clone(); TopDown.sort(a); assertArrayEquals(expected, a);
a = input.clone(); BottomUp.sort(a); assertArrayEquals(expected, a);
a = input.clone(); SkipSorted.sort(a); assertArrayEquals(expected, a);
assertArrayEquals(expected, values(ListMergeSort.sort(ListMergeSort.of(input)), n));
assertArrayEquals(expected, values(ListMergeSort.sortBottomUp(ListMergeSort.of(input)), n));
assertEquals(Inversions.bruteForce(input), Inversions.count(input));
}
record Item(int key, int id) {}
@Test
void everySmallArrayAndManyRandomOnes() {
long exhaustive = 0;
for (int n = 0; n <= 8; n++) {
int total = (int) Math.pow(5, n); // every array of length n over 5 values
for (int code = 0; code < total; code++) {
int[] a = new int[n];
for (int i = 0, c = code; i < n; i++, c /= 5) a[i] = c % 5;
check(a);
exhaustive++;
}
}
Random r = new Random(2026);
int random = 20_000;
for (int k = 0; k < random; k++) {
int n = r.nextInt(200);
int range = r.nextBoolean() ? 8 : 1_000_000;
check(r.ints(n, -range, range).toArray());
}
int stable = 5_000;
Comparator<Item> byKey = Comparator.comparingInt(Item::key);
for (int k = 0; k < stable; k++) {
Item[] items = new Item[r.nextInt(100)];
for (int i = 0; i < items.length; i++) items[i] = new Item(r.nextInt(5), i);
Item[] expected = items.clone();
Arrays.sort(expected, byKey);
Stability.sort(items, byKey, true);
assertArrayEquals(expected, items);
}
assertEquals(488_281, exhaustive);
Transcript t = Transcript.start("08-brute-force.txt", "Cross-checks against Arrays.sort and the O(n^2) inversion definition");
t.line(String.format("every array of length 0..8 over 5 values: %,d arrays", exhaustive));
t.line(String.format("random arrays, length 0..199 (seed 2026): %,d arrays", random));
t.line("each checked: top-down, bottom-up, skip-sorted, linked list (top-down), linked list (bottom-up), inversion count");
t.line("disagreements: 0").blank();
t.line(String.format("stability, records with 5 distinct keys: %,d arrays, same object order as Arrays.sort(T[], Comparator): 0 disagreements", stable));
t.flush();
}
}
@@ -0,0 +1,88 @@
package com.ankurm.interviewlab.mergesort;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import com.ankurm.interviewlab.mergesort.support.Data;
import com.ankurm.interviewlab.mergesort.support.Transcript;
import org.junit.jupiter.api.Test;
class ComplexityTest {
static int ceilLog2(int n) {
return 32 - Integer.numberOfLeadingZeros(n - 1);
}
/** Exact worst case of top-down merge sort: n*ceil(lg n) - 2^ceil(lg n) + 1. */
static long bound(int n) {
return n < 2 ? 0 : (long) n * ceilLog2(n) - (1L << ceilLog2(n)) + 1;
}
@Test
void worstCaseFormulaIsExact() {
for (int n = 1; n <= 3000; n++) {
assertEquals(bound(n), Measured.topDown(Data.worstCase(n)), "n=" + n);
}
// and it really is the maximum: try every permutation up to n = 9
for (int n = 1; n <= 9; n++) {
long[] max = {0};
permute(Data.sorted(n), 0, p -> max[0] = Math.max(max[0], Measured.topDown(p.clone())));
assertEquals(bound(n), max[0]);
}
}
static void permute(int[] a, int k, java.util.function.Consumer<int[]> use) {
if (k == a.length) {
use.accept(a);
return;
}
for (int i = k; i < a.length; i++) {
int t = a[k]; a[k] = a[i]; a[i] = t;
permute(a, k + 1, use);
t = a[k]; a[k] = a[i]; a[i] = t;
}
}
@Test
void comparisonCounts() {
Transcript t = Transcript.start("07-comparison-counts.txt", "Element comparisons. random = new Random(7).nextInt(); worst = built by Data.worstCase");
t.line(String.format("%9s %-9s %12s %12s %12s %12s", "n", "input", "top-down", "bottom-up", "skip-sorted", "worst bound"));
for (int n : new int[] {1_000, 1_024, 100_000, 1_048_576}) {
String[] names = {"random", "sorted", "reversed", "worst"};
int[][] inputs = {Data.random(n, 7), Data.sorted(n), Data.reversed(n), Data.worstCase(n)};
for (int k = 0; k < names.length; k++) {
long td = Measured.topDown(inputs[k].clone());
long bu = Measured.bottomUp(inputs[k].clone());
long sk = Measured.skipSorted(inputs[k].clone());
assertTrue(td <= bound(n));
if (names[k].equals("sorted")) assertEquals(n - 1, sk);
if (Integer.bitCount(n) == 1) {
assertEquals(td, bu);
if (names[k].equals("sorted")) assertEquals((long) n / 2 * ceilLog2(n), td);
}
t.line(String.format("%,9d %-9s %,12d %,12d %,12d %,12d", n, names[k], td, bu, sk, bound(n)));
}
}
t.flush();
}
@Test
void againstQuickSort() {
Transcript t = Transcript.start("11-merge-vs-quick.txt", "Comparisons: top-down merge sort vs randomized Lomuto quick sort (pivot seed 1)");
t.line(String.format("%9s %-18s %14s %16s", "n", "input", "merge sort", "quick sort"));
for (int n : new int[] {1_000, 10_000, 100_000}) {
int[] random = Data.random(n, 7);
long m = Measured.topDown(random.clone()), q = Measured.quick(random.clone(), 1);
assertTrue(m < q);
t.line(String.format("%,9d %-18s %,14d %,16d", n, "random", m, q));
}
int n = 20_000;
int[] few = new int[n];
var r = new java.util.Random(7);
for (int i = 0; i < n; i++) few[i] = r.nextInt(10);
long m = Measured.topDown(few.clone()), q = Measured.quick(few.clone(), 1);
assertTrue(q > 10 * m);
t.line(String.format("%,9d %-18s %,14d %,16d", n, "10 distinct keys", m, q));
t.flush();
}
}
@@ -0,0 +1,62 @@
package com.ankurm.interviewlab.mergesort;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import com.ankurm.interviewlab.mergesort.support.Transcript;
import java.util.Arrays;
import java.util.List;
import org.junit.jupiter.api.Test;
class DryRunTest {
static final int[] SAMPLE = {38, 27, 43, 3, 9, 82, 10};
static final int[] SORTED = {3, 9, 10, 27, 38, 43, 82};
@Test
void topDown() {
Transcript t = Transcript.start("01-dry-run-top-down.txt", "Top-down merge sort on " + Arrays.toString(SAMPLE) + ": merges in execution order");
int[] a = SAMPLE.clone();
List<DryRun.Merge> merges = DryRun.topDown(a);
assertArrayEquals(SORTED, a);
assertEquals(6, merges.size());
int total = 0, k = 1;
for (DryRun.Merge m : merges) {
t.line(String.format("%d. a[%d..%d] %-14s + %-14s -> %-30s %d comparisons", k++, m.lo(), m.hi(), m.left(), m.right(), m.result(), m.comparisons()));
t.line(" array now " + m.array());
total += m.comparisons();
}
assertEquals(14, total);
t.blank().line("total: " + merges.size() + " merges, " + total + " comparisons").flush();
}
@Test
void oneMerge() {
int[] runs = {3, 27, 38, 43, 9, 10, 82};
Transcript t = Transcript.start("02-dry-run-final-merge.txt", "The last merge, element by element: [3, 27, 38, 43] + [9, 10, 82]");
List<String> steps = DryRun.mergeSteps(runs, 3);
assertEquals(7, steps.size());
steps.forEach(t::line);
t.flush();
}
@Test
void bottomUp() {
Transcript t = Transcript.start("03-dry-run-bottom-up.txt", "Bottom-up merge sort on " + Arrays.toString(SAMPLE) + ": one block per pass");
int[] a = SAMPLE.clone();
List<List<DryRun.Merge>> passes = DryRun.bottomUp(a);
assertArrayEquals(SORTED, a);
assertEquals(3, passes.size());
int width = 1, total = 0;
for (List<DryRun.Merge> pass : passes) {
t.line("pass with width " + width + ":");
for (DryRun.Merge m : pass) {
t.line(String.format(" %-18s + %-14s -> %s", m.left(), m.right(), m.result()));
total += m.comparisons();
}
t.line(" array after the pass " + pass.getLast().array());
width *= 2;
}
t.blank().line("total comparisons: " + total).flush();
}
}
@@ -0,0 +1,66 @@
package com.ankurm.interviewlab.mergesort;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import com.ankurm.interviewlab.mergesort.support.Data;
import com.ankurm.interviewlab.mergesort.support.Transcript;
import java.util.Arrays;
import org.junit.jupiter.api.Test;
class InversionsTest {
/** The wrong tie rule: counts a pair of EQUAL values as an inversion. */
static long countWithStrictLeft(int[] a, int lo, int hi) {
if (lo >= hi) return 0;
int mid = lo + (hi - lo) / 2;
long total = countWithStrictLeft(a, lo, mid) + countWithStrictLeft(a, mid + 1, hi);
int[] copy = Arrays.copyOfRange(a, lo, hi + 1);
int i = 0, j = mid - lo + 1, left = j;
for (int k = lo; k <= hi; k++) {
if (i >= left) a[k] = copy[j++];
else if (j >= copy.length) a[k] = copy[i++];
else if (copy[i] < copy[j]) a[k] = copy[i++];
else { total += left - i; a[k] = copy[j++]; }
}
return total;
}
@Test
void examples() {
Transcript t = Transcript.start("10-inversions.txt", "Counting inversions");
for (int[] a : new int[][] {{2, 4, 1, 3, 5}, {38, 27, 43, 3, 9, 82, 10}, {1, 2, 3, 4, 5}, {5, 4, 3, 2, 1}}) {
assertEquals(Inversions.bruteForce(a), Inversions.count(a));
t.line(String.format("%-30s %d", Arrays.toString(a), Inversions.count(a)));
}
assertEquals(3, Inversions.count(new int[] {2, 4, 1, 3, 5}));
int n = 100_000;
long big = Inversions.count(Data.reversed(n));
assertEquals((long) n * (n - 1) / 2, big);
assertTrue((int) big != big);
t.blank().line(String.format("reversed array, n = 100,000: %,d (Integer.MAX_VALUE = %,d)", big, Integer.MAX_VALUE));
t.line(String.format("the same total kept in an int: %,d", (int) big)).blank();
int[] equal = {7, 7, 7, 7};
long wrong = countWithStrictLeft(equal.clone(), 0, 3);
assertEquals(0, Inversions.count(equal));
assertEquals(6, wrong);
t.line("[7, 7, 7, 7] ties take left : " + Inversions.count(equal));
t.line("[7, 7, 7, 7] ties take right: " + wrong + " (wrong: equal values are not an inversion)");
t.flush();
}
@Test
void midpoint() {
int lo = 1_200_000_000, hi = 1_500_000_000;
assertTrue((lo + hi) / 2 < 0);
assertEquals(1_350_000_000, lo + (hi - lo) / 2);
Transcript t = Transcript.start("13-midpoint.txt", "The midpoint, with indices near the top of the int range (arithmetic only, no array allocated)");
t.line("lo = 1,200,000,000 hi = 1,500,000,000");
t.line(String.format("(lo + hi) / 2 = %,d", (lo + hi) / 2));
t.line(String.format("lo + (hi - lo) / 2 = %,d", lo + (hi - lo) / 2));
t.line(String.format("(lo + hi) >>> 1 = %,d", (lo + hi) >>> 1));
t.flush();
}
}
@@ -0,0 +1,78 @@
package com.ankurm.interviewlab.mergesort;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import com.ankurm.interviewlab.mergesort.support.Data;
import com.ankurm.interviewlab.mergesort.support.Transcript;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.List;
import java.util.zip.ZipFile;
import org.junit.jupiter.api.Test;
/** What Arrays.sort really does on this JDK, read from lib/src.zip and measured through a counting comparator. */
class JdkSortTest {
static List<String> source(String name) throws IOException {
try (ZipFile zip = new ZipFile(Path.of(System.getProperty("java.home"), "lib", "src.zip").toFile())) {
var entry = zip.getEntry("java.base/java/util/" + name + ".java");
return new String(zip.getInputStream(entry).readAllBytes(), StandardCharsets.UTF_8).lines().toList();
}
}
static void quote(Transcript t, String file, String signature, int count) throws IOException {
List<String> lines = source(file);
int at = -1;
for (int i = 0; i < lines.size(); i++) {
if (lines.get(i).contains(signature)) { at = i; break; }
}
assertTrue(at >= 0, signature);
t.line(file + ".java, line " + (at + 1) + ":");
lines.subList(at, at + count).forEach(t::line);
t.blank();
}
@Test
void sourceOfTheRunningJdk() throws IOException {
Transcript t = Transcript.start("12-jdk-arrays-sort.txt", "From lib/src.zip of Java " + System.getProperty("java.version"));
quote(t, "Arrays", "public static void sort(int[] a) {", 3);
quote(t, "Arrays", "public static void sort(Object[] a) {", 6);
quote(t, "Arrays", "java.util.Arrays.useLegacyMergeSort", 1);
quote(t, "TimSort", "private static final int MIN_MERGE", 1);
t.flush();
}
static long jdk(int[] input) {
Integer[] boxed = Arrays.stream(input).boxed().toArray(Integer[]::new);
long[] count = {0};
Arrays.sort(boxed, (x, y) -> { count[0]++; return Integer.compare(x, y); });
return count[0];
}
@Test
void timSortExploitsExistingOrder() {
int n = 100_000;
int[] runs = Data.random(n, 7);
for (int i = 0; i < 4; i++) Arrays.sort(runs, i * n / 4, (i + 1) * n / 4);
int[] nearly = Data.sorted(n);
var r = new java.util.Random(7);
for (int k = 0; k < 10; k++) {
int x = r.nextInt(n), y = r.nextInt(n), v = nearly[x];
nearly[x] = nearly[y];
nearly[y] = v;
}
String[] names = {"random", "sorted", "reversed", "4 sorted runs", "sorted, 10 swaps"};
int[][] inputs = {Data.random(n, 7), Data.sorted(n), Data.reversed(n), runs, nearly};
Transcript t = Transcript.start("14-timsort-comparisons.txt", "Comparisons for n = 100,000: our merge sort vs Arrays.sort(Integer[], countingComparator)");
t.line(String.format("%-18s %12s %12s %14s", "input", "top-down", "skip-sorted", "Arrays.sort"));
for (int k = 0; k < names.length; k++) {
long td = Measured.topDown(inputs[k].clone()), sk = Measured.skipSorted(inputs[k].clone()), j = jdk(inputs[k]);
if (names[k].equals("sorted") || names[k].equals("reversed")) assertEquals(n - 1, j);
t.line(String.format("%-18s %,12d %,12d %,14d", names[k], td, sk, j));
}
t.flush();
}
}
@@ -0,0 +1,81 @@
package com.ankurm.interviewlab.mergesort;
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.mergesort.legacy.Original2015;
import com.ankurm.interviewlab.mergesort.support.Data;
import com.ankurm.interviewlab.mergesort.support.Transcript;
import java.io.IOException;
import java.lang.management.ManagementFactory;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.Random;
import org.junit.jupiter.api.Test;
/** The 2015 program of this article: what it prints, that it sorts correctly, and what it allocates. */
class LegacyTest {
static String run(String file, String stdin) throws IOException, InterruptedException {
String java = Path.of(System.getProperty("java.home"), "bin", "java").toString();
Process p = new ProcessBuilder(java, file).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);
assertEquals(0, p.waitFor());
return out;
}
@Test
void originalProgramStillPrintsItsSampleOutput() throws Exception {
String out = run("legacy/MergeSort.java", "5\n38\n27\n43\n3\n9\n");
assertTrue(out.endsWith("Sorted array:\n3\n9\n27\n38\n43\n"), out);
Transcript t = Transcript.start("05-original-2015-program.txt", "java legacy/MergeSort.java, typing 5, 38, 27, 43, 3, 9 (the sample of the 2015 article)");
t.line(out.stripTrailing()).flush();
}
@Test
void copyInSrcIsTheSameLogic() throws IOException {
String original = Files.readString(Path.of("legacy/MergeSort.java"));
String copy = Files.readString(Path.of("src/main/java/com/ankurm/interviewlab/mergesort/legacy/Original2015.java"));
String from = " * Merges two adjacent";
String methods = original.substring(original.indexOf(from), original.indexOf(" public static void main"))
.replace(" static void", " public static void").stripTrailing();
assertTrue(copy.contains(methods));
}
@Test
void correctButAllocatesAQuadraticAmount() {
Random r = new Random(2015);
for (int k = 0; k < 10_000; k++) {
int[] a = r.ints(r.nextInt(30), -5, 6).toArray();
int[] expected = a.clone();
Arrays.sort(expected);
Original2015.mergeSort(a, 0, a.length - 1);
assertArrayEquals(expected, a);
}
var bean = (com.sun.management.ThreadMXBean) ManagementFactory.getThreadMXBean();
Transcript t = Transcript.start("06-original-allocation.txt", "new int[arr.length] inside merge(): elements allocated, and bytes measured with ThreadMXBean (MB = 1,000,000 bytes)");
t.line("10,000 seeded random arrays sorted by the 2015 methods vs Arrays.sort: 0 disagreements.").blank();
t.line(String.format("%8s %8s %20s %18s %18s", "n", "merges", "int slots allocated", "2015 measured", "one shared buffer"));
for (int n : new int[] {1_000, 10_000, 40_000}) {
int[] a = Data.random(n, 7);
int[] b = a.clone();
long s = bean.getCurrentThreadAllocatedBytes();
Original2015.mergeSort(a, 0, n - 1);
long old = bean.getCurrentThreadAllocatedBytes() - s;
s = bean.getCurrentThreadAllocatedBytes();
TopDown.sort(b);
long fixed = bean.getCurrentThreadAllocatedBytes() - s;
assertArrayEquals(a, b);
long slots = (long) (n - 1) * n;
assertTrue(old >= 4 * slots && old < 4 * slots * 1.05 + 100_000, "old " + old);
assertTrue(fixed < 4L * n + 100_000, "fixed " + fixed);
t.line(String.format("%,8d %,8d %,20d %,15.1f MB %,15.2f MB", n, n - 1, slots, old / 1e6, fixed / 1e6));
}
t.flush();
}
}
@@ -0,0 +1,56 @@
package com.ankurm.interviewlab.mergesort;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import com.ankurm.interviewlab.mergesort.ListMergeSort.Node;
import com.ankurm.interviewlab.mergesort.support.Data;
import com.ankurm.interviewlab.mergesort.support.Transcript;
import java.util.Collections;
import java.util.IdentityHashMap;
import java.util.Set;
import org.junit.jupiter.api.Test;
class LinkedListTest {
static String show(Node head) {
StringBuilder b = new StringBuilder();
for (Node p = head; p != null; p = p.next) b.append(p.value).append(" -> ");
return b.append("null").toString();
}
static Set<Node> nodes(Node head) {
Set<Node> s = Collections.newSetFromMap(new IdentityHashMap<>());
for (Node p = head; p != null; p = p.next) s.add(p);
return s;
}
@Test
void relinksTheSameNodes() {
Node head = ListMergeSort.of(38, 27, 43, 3, 9, 82, 10);
String before = show(head);
Set<Node> original = nodes(head);
Node sorted = ListMergeSort.sort(head);
assertEquals(original, nodes(sorted));
int n = 1_000_000;
int[] values = Data.random(n, 7);
int[] expected = values.clone();
java.util.Arrays.sort(expected);
assertArrayEquals(expected, AgreementTest.values(ListMergeSort.sort(ListMergeSort.of(values)), n));
assertArrayEquals(expected, AgreementTest.values(ListMergeSort.sortBottomUp(ListMergeSort.of(values)), n));
Transcript t = Transcript.start("09-linked-list.txt", "Merge sort on a singly linked list");
t.line("before " + before);
t.line("after " + show(sorted));
t.line("same 7 node objects, relinked: true").blank();
t.line("1,000,000 random values: top-down and bottom-up both match Arrays.sort").blank();
assertThrows(StackOverflowError.class, () -> BrokenSplit.sort(ListMergeSort.of(2, 1)));
t.line("split written with fast = head (instead of head.next), input 2 -> 1 -> null:");
t.line(" java.lang.StackOverflowError");
t.flush();
}
}
@@ -0,0 +1,26 @@
package com.ankurm.interviewlab.mergesort;
import static org.junit.jupiter.api.Assertions.assertTrue;
import com.ankurm.interviewlab.mergesort.support.Transcript;
import org.junit.jupiter.api.Test;
/** Runs download/MergeSort.java the way a reader would. */
class SingleFileTest {
@Test
void sampleSessions() throws Exception {
Transcript t = Transcript.start("15-single-file-sessions.txt", "java download/MergeSort.java, with two inputs typed in");
String[][] sessions = {
{"5\n38\n27\n43\n3\n9\n", "[3, 9, 27, 38, 43]", "7"},
{"7\n38\n27\n43\n3\n9\n82\n10\n", "[3, 9, 10, 27, 38, 43, 82]", "11"},
};
for (String[] s : sessions) {
String out = LegacyTest.run("download/MergeSort.java", s[0]);
assertTrue(out.contains("Top-down: " + s[1]) && out.contains("Bottom-up: " + s[1]), out);
t.line("typed: " + s[0].strip().replace("\n", " "));
t.line(out.stripTrailing()).blank();
}
t.flush();
}
}
@@ -0,0 +1,39 @@
package com.ankurm.interviewlab.mergesort;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import com.ankurm.interviewlab.mergesort.support.Transcript;
import java.util.Arrays;
import java.util.Comparator;
import org.junit.jupiter.api.Test;
class StabilityTest {
record Student(String name, int marks) {
@Override public String toString() { return name + ":" + marks; }
}
@Test
void oneCharacterDecidesStability() {
Student[] input = {new Student("Asha", 82), new Student("Bala", 75), new Student("Chitra", 82), new Student("Dev", 75), new Student("Esha", 90)};
Comparator<Student> byMarks = Comparator.comparingInt(Student::marks);
Student[] left = input.clone();
Stability.sort(left, byMarks, true);
Student[] strict = input.clone();
Stability.sort(strict, byMarks, false);
Student[] jdk = input.clone();
Arrays.sort(jdk, byMarks);
assertArrayEquals(jdk, left);
assertFalse(Arrays.equals(jdk, strict));
Transcript t = Transcript.start("04-stability.txt", "Sorting students by marks only: equal marks should keep their input order");
t.line("input " + Arrays.toString(input));
t.line("ties take LEFT (cmp <= 0) " + Arrays.toString(left));
t.line("Arrays.sort(T[], Comparator) " + Arrays.toString(jdk));
t.line("ties take RIGHT (cmp < 0) " + Arrays.toString(strict) + " <- the 2015 rule: not stable");
t.flush();
}
}
@@ -0,0 +1,51 @@
package com.ankurm.interviewlab.mergesort.support;
import java.util.Random;
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();
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;
}
/** An input that forces every merge of top-down merge sort to make the maximum number of comparisons. */
public static int[] worstCase(int n) {
return unmerge(sorted(n));
}
private static int[] unmerge(int[] s) {
int n = s.length;
if (n < 2) return s;
int[] left = new int[(n + 1) / 2];
int[] right = new int[n / 2];
// hand out the values alternately from the top, so both runs survive until the last two elements
int l = left.length - 1, r = right.length - 1;
boolean toLeft = true;
for (int k = n - 1; k >= 0; k--) {
if ((toLeft && l >= 0) || r < 0) left[l--] = s[k];
else right[r--] = s[k];
toLeft = !toLeft;
}
int[] a = unmerge(left), b = unmerge(right);
int[] out = new int[n];
System.arraycopy(a, 0, out, 0, a.length);
System.arraycopy(b, 0, out, a.length, b.length);
return out;
}
}
@@ -0,0 +1,43 @@
package com.ankurm.interviewlab.mergesort.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<String> 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);
}
}
}