Skip to main content

Quick Sort in Java: Lomuto vs Hoare Partition, Dry Run and Complexity

Quick Sort in Java with both the Lomuto and Hoare partition, traced step by step on the same array, then measured: comparisons, swaps and recursion depth on random, sorted, reverse-sorted, all-equal and few-distinct-key input. Covers random pivots, three-way partitioning, recursing into the smaller side, what Arrays.sort really does, and two bugs found in the 2015 versions of this post.

You have an array of numbers and you have to sort it yourself — for a practical, for an interview, or because Arrays.sort feels like cheating. Quick Sort is the algorithm everyone names, and the one almost everyone gets subtly wrong the first time. The idea fits in one sentence: pick one element (the pivot), rearrange the array so that everything smaller is on its left and everything larger is on its right, then do the same thing to the left part and to the right part.

The interesting part is the rearranging step, called partitioning, because there are two classic ways to write it — Lomuto and Hoare — and they behave differently in ways that only show up when you count comparisons, swaps and stack frames. This article builds both, traces them by hand on the same six numbers, measures them on the inputs that hurt, and then goes back to the 2015 versions of this post to show what they got wrong. Every number below comes from a file that a test wrote; each one is linked.

Versions and what this replaces. Everything was compiled and run on Temurin JDK 25.0.5.1+2 (LTS) with JUnit 6.1.3, the latest GA on Maven Central. Quick Sort was developed by Tony Hoare in 1959 and published in 1961 (CACM, July 1961, Algorithms 63–65). This article merges three older ankurm.com posts into one; the other two URLs now redirect here. Code: java-interview-lab/quick-sort · single-file program: download QuickSort.java.

Quick Sort in one picture: put one key in its final place, then repeat on both sides

Take [15, 34, 26, 67, 95, 24] and choose the last element, 24, as the pivot. One pass over the array moves everything that is not larger than 24 to the front, and then the pivot drops into the gap. After that single pass, 24 is exactly where it will be in the final sorted array. Nothing else is guaranteed — the right part is still a mess — and that is fine, because it is now a smaller problem of the same shape.

Before: pick the last element (24) as the pivot153426679524one pass over the array, moving every key that is not larger than 24 to the frontAfter one partition15242667953415 (blue) is smaller; 24 (green) is in its final slot, index 1; the right part (grey) is not sorted yetQuick Sort now repeats the same trick on the left part (one element, done) and on the right part (four elements).

The picture is the whole algorithm: divide (partition around the pivot), conquer (sort the two parts the same way), and there is nothing to combine, because the pieces already sit in the right order inside the original array. That in-place property is why Quick Sort needs no second array, unlike merge sort. When a part has zero or one elements it is already sorted, and the recursion stops.

Here is a complete program you can compile and run. It reads the numbers, sorts a copy with each of the three variants this article covers (Lomuto, Hoare and Lomuto with a random pivot), and prints all three. The code is also in the repository as download/QuickSort.java, and the same file is attached to this article: download QuickSort.java.

Full program: QuickSort.java (click to open, or download it)
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));
    }
}

Running it on the sample input of the 2015 six-element post (transcript: output/14-single-file-sessions.txt):

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]

All three agree, which is the minimum you should ask of any sorting code. How they differ is the rest of the article.

Going deeper

Lomuto partition: one pointer scans, another marks the end of the “small” zone

Lomuto is the version most textbooks and interview answers use, because it is short and each variable has one job. The pivot is the last element. A scanning pointer j walks left to right; a second pointer i marks the last index of the zone of keys that are <= pivot. Whenever a[j] belongs in that zone, i moves one step and the two elements swap. When the scan ends, the pivot swaps into the gap right after the zone.

This is Lomuto.java in full:

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;
    }
}

Notice the recursion: sort(a, lo, p - 1) and sort(a, p + 1, hi). The pivot is excluded from both calls, because partition returned its final index. Keep that sentence in mind for the next section, where the same line of code is a bug.

Here is what happens on [15, 34, 26, 67, 95, 24]. The first partition looks at five keys: 15 is small, the other four are larger, so only i moves once and the pivot swaps with index 1. Two more partitions finish the job — three partition calls in total. The full step-by-step trace is below, quoted from output/01-dry-run-lomuto.txt:

Dry run: Lomuto on [15, 34, 26, 67, 95, 24] (every compare and swap)
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
Read the swaps that swap a slot with itself. The first line of the trace says swap a[0] and a[0]. That is not a typo: i and j start at the same place, so the first small key swaps with itself. It costs nothing, but it is why a naive “count the swaps” on Lomuto overstates the work. The measurements later in this article skip self-swaps.

Why <= and not <? Either is correct, but they treat keys equal to the pivot differently, and that choice decides how Lomuto behaves on arrays full of duplicates — the equal-keys section below is about exactly that. Why the last element as pivot? Only because it is convenient: it is out of the way while j scans. It is also the choice that makes already-sorted input the worst case, which is the worst-case section below.

Going deeper

  • The dry-run code itself (an instrumented copy that records each step and is cross-checked against the real sort): DryRuns.java.
  • Why the 2015 post that used this algorithm is also correct, and was checked against this clean version on 5,000 random arrays: legacy/LomutoQuickSort2015.java.

Hoare partition: two pointers walk toward each other and swap what is on the wrong side

Hoare’s own partition came first; Lomuto’s is the simplification that textbooks later adopted. Instead of one scanning pointer, there are two: i starts at the left end and moves right until it finds a key that is not smaller than the pivot; j starts at the right end and moves left until it finds a key that is not larger. Those two keys are on the wrong sides, so they swap, and the walk continues until the pointers meet or cross.

Lomuto: j walks right, i marks the end of the small zone153426679524i,jpivot = 24 (last). 15 is small, so i moves; every other key is larger, so only j moves. Finally 24 swaps with a[i+1].Hoare: i walks right, j walks left, stop and swap153426679524ijpivot = 26 (middle, green). i stops at 34 (it is not smaller than 26), j stops at 24 (it is not larger).Both are on the wrong side, so they swap: [15, 24, 26, 67, 95, 34]. Then the pointers keep walking until they meet.Lomuto fixes one pivot per pass; Hoare moves pairs of misplaced keys, which is why it swaps less.

The diagram puts the two schemes on the same array. Lomuto does one unit of work per key and fixes exactly one thing per pass — the pivot’s position. Hoare fixes pairs of misplaced keys, so each swap puts two keys on the correct side at once. Hoare also uses the middle element as the pivot, which is the first line of defence against sorted input.

The code, in full, from Hoare.java:

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.
 *
 * <p>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);
        }
    }
}
The returned index is not the pivot’s final position. Lomuto’s partition returns the pivot’s final index, so the recursion skips it. Hoare’s returns only a split point: everything in [lo..p] is <= everything in [p+1..hi]. So the recursion is (lo, p) and (p + 1, hi) — p stays on the left. Copying Lomuto’s (lo, p - 1) into a Hoare sort is the single most common Hoare bug; it is reproduced below.

The trace on the same six numbers, from output/02-dry-run-hoare.txt, needs five partition calls where Lomuto needed three — each call is smaller, but there are more of them:

Dry run: Hoare 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

Two Hoare variants that look reasonable and are wrong, reproduced by Pitfalls.java (output: output/12-pitfalls.txt):

Two Hoare mistakes, reproduced
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]

The first mistake never terminates: with the last element as the pivot, the partition can return hi itself, and (lo, p) is then the same range again. That is why Hoare’s version above uses the middle element rounded down. The second mistake is quieter: it returns a plausible array with a key out of place: 52 of the 120 permutations of five numbers come back out of order. Small inputs that happen to work are exactly how this bug survives a quick test.

Going deeper

Which one is faster? Count comparisons and swaps instead of guessing

Both schemes are O(n log n) on average, so the useful question is what each one spends its effort on. Measured.java holds copies of the sorts that count comparisons (an element against the pivot) and swaps (two different positions), and every run is checked against Arrays.sort so the counting cannot change the algorithm. Random keys, seed 7, from output/07-lomuto-vs-hoare-random.txt:

nSchemeComparisonsSwaps
1,000Lomuto10,1284,547
Hoare15,6792,301
10,000Lomuto155,16866,283
Hoare193,95830,750
100,000Lomuto2,050,0861,016,714
Hoare2,377,190387,156

The result is a trade, not a winner: at n = 100,000 Hoare does 0.38 times the swaps of Lomuto but about 16% more comparisons. Which one is faster on a real machine depends on how expensive a swap is next to a comparison, and this article did not time it — timing a JVM properly needs a benchmark harness, and a number from a quick loop would be exactly the kind of figure this blog tries not to print. What the counts do show is that “Hoare is faster” is a claim about swaps, not about everything.

Both schemes also handle the other two 2015 inputs, including the one with duplicates (output/03-both-on-the-2015-samples.txt):

Both partitions on the 7-element and 9-element samples
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)

Going deeper

The worst case: when every partition peels off a single key

Quick Sort is fast when each partition splits the array into two reasonably equal halves, because then the recursion is about log2(n) levels deep and each level touches n keys. It is slow when a partition splits 1 : n-1, because then the recursion is n levels deep and the total is n + (n-1) + … + 1, about n²/2 comparisons. A pivot that is always the smallest or largest key in its range produces exactly that.

Already-sorted input, n = 5,000 (from output/06-worst-case.txt)Last element as pivot (Lomuto)every partition peels off one key: 5,000 levels, 12,497,500 comparisonsMiddle element as pivot (Hoare)the range halves each time: 14 levels, 66,807 comparisonsSame keys, same algorithm family. Only the choice of pivot changed, and the cost went from 12.5 million to 67 thousand.The 5,000-deep column is also a stack problem: each level is a method call that has not returned yet.Bars are schematic (a few levels of each shape); the numbers are the measured ones.

The left column is Lomuto on input that is already sorted: the last element is the largest, so every partition puts all the other keys on one side. The right column is Hoare with its middle pivot on the same input. The labels are the measured numbers from the table below; the bars only sketch the shape.

Four schemes against five kinds of input, n = 5,000, from output/06-worst-case.txt. For reference, n(n-1)/2 is 12,497,500 for this n.

Input (n = 5,000)SchemeComparisonsSwapsDeepest recursion
randomLOMUTO_LAST74,22138,78132
LOMUTO_RANDOM72,50332,02227
HOARE_MIDDLE86,17014,46427
THREE_WAY114,97546,95326
already sortedLOMUTO_LAST12,497,50005,000
LOMUTO_RANDOM68,4224,94827
HOARE_MIDDLE66,807014
THREE_WAY86,51128,25419
reverse sortedLOMUTO_LAST12,497,5002,5005,000
LOMUTO_RANDOM71,48331,55628
HOARE_MIDDLE66,8082,50014
THREE_WAY86,14228,03019
all equalLOMUTO_LAST12,497,50005,000
LOMUTO_RANDOM12,497,5004,9915,000
HOARE_MIDDLE69,60629,80414
THREE_WAY10,00002
10 distinct keysLOMUTO_LAST1,266,1997,876545
LOMUTO_RANDOM1,266,49014,752542
HOARE_MIDDLE77,65125,33421
THREE_WAY35,96914,7057
Three things the table says, and one it does not. (1) Lomuto with the last element as pivot hits exactly 12,497,500 comparisons on sorted, reverse-sorted and all-equal input — the test asserts the equality. (2) A random pivot fixes sorted and reverse-sorted input (about 70,000 comparisons) but not all-equal input: every key is <= the pivot whatever the pivot is, so it is still 12,497,500. (3) Hoare is not hurt by equal keys, because both of its pointers stop on a key equal to the pivot, which keeps the split balanced. What the table does not say is that Hoare with a middle pivot is immune: it is just that the usual bad inputs are not bad for it. In principle a crafted input can still defeat any fixed pivot rule.

Random pivots are not magic either, but they take away the “bad input”: whatever order the data arrives in, the cost depends on the random draws. Twenty seeds on the sorted input from output/08-randomized-pivot.txt:

Lomuto, last element as pivot: 12,497,500 comparisons

over 20 seeds: min 67,134, max 85,451 comparisons, deepest recursion 34
n * log2(n) = 61,439
Full table as the test printed it, and all 20 seeds

output/06-worst-case.txt

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

output/08-randomized-pivot.txt

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

Going deeper

  • The random-pivot sort: Randomized.java. Seeded in the tests so every run prints the same numbers.
  • Median-of-three and other pivot rules are not covered here; the exact input that defeats a given rule is the thing to test before trusting it.

Equal keys: Lomuto’s quiet quadratic, and the three-way partition

Duplicates are the input where the two schemes differ most, and a very ordinary one: ages, marks, ratings, status codes. Here are 20,000 keys that take only 10 distinct values (from output/09-three-way-duplicates.txt):

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

Lomuto spends 20 million comparisons and recurses 2,082 levels deep, because each block of roughly 2,000 equal keys behaves like the all-equal case. Hoare needs 338,316 comparisons and 23 levels. The three-way partition (Dijkstra’s “Dutch national flag”) needs 102,334 and 6: it splits the range into smaller | equal | larger and never looks at the equal block again. On the all-equal 5,000-key input from the previous table it finishes in 10,000 comparisons, which is two looks at each key and no swaps.

The three-way version, from ThreeWay.java:

ThreeWay.java (Dijkstra three-way partition)
package com.ankurm.interviewlab.quicksort;

/** Dijkstra's three-way partition (Dutch national flag): &lt; pivot | == pivot | &gt; 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);
    }
}

Going deeper

  • Why the all-equal run in the table costs exactly 2 × n comparisons: output/06-worst-case.txt (row all equal, THREE_WAY).
  • The bug in the 2015 temp-array version is also about duplicates, in a much worse way: next section.

Stack depth: the worst case can kill the thread, not just slow it

Every level of the recursion is a method call that has not returned. On sorted input with the last element as pivot that is about n calls waiting at once, and the JVM’s stack is finite. The test runs the sort on a thread with a deliberately small 256 KB stack so the failure is quick and repeatable (output/10-stack-depth.txt):

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).

The fix is a classic: recurse into the smaller side and loop on the larger one. Each recursive call at least halves the range, so the stack holds at most about log2(n) frames whatever the pivot does — here the deepest recursion is 2. This does not make the sort faster (the quadratic comparison count is still there on sorted input); it only guarantees the stack cannot be the thing that fails. From StackSafe.java:

StackSafe.java (recurse into the smaller side)
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;
    }
}
The depth at which a StackOverflowError appears is not a constant. It depends on the JVM, the JIT state and -Xss, so do not quote “Java overflows at 10,000 levels”. What is stable, and what the test pins, is that plain recursion needs on the order of n frames here and the smaller-side version needs only a handful.

Going deeper

  • The test: StackTest.java; it also sorts five input shapes of 20,000 keys with the stack-safe version and compares each with Arrays.sort.

What the 2015 versions of this post got wrong

This article replaces three posts from 2015. Rebuilding them on the same test bench found a real bug in two of them. Neither bug shows on the sample input the old post printed, which is why they survived eleven years.

The temp-array version silently corrupts arrays that contain duplicates

The old “Implementing Quick Sort in Java” post copied the keys smaller than the pivot into a temporary array, then the pivot, then the keys larger than the pivot — and no pass handled keys equal to the pivot, other than the pivot itself. The logic is kept unchanged in legacy/TempArrayQuickSort.java. Output from output/04-legacy-temp-array.txt:

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.

For [3, 1, 3, 2] the second 3 never reaches the temporary array, and the leftover slot keeps the 0 it was initialised with. The output is not merely unsorted; it contains a number that was never in the input. The temp array is also allocated at the size of the whole array on every call, which is where the O(n) extra space per call came from.

The 2015 temp-array code, logic unchanged
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);
        }
    }
}

The first-pivot version throws when the pivot is the largest key at the end of the array

The older “Implementing Quicksort Algorithm in Java” post used the first element as pivot and two pointers. Its inner loop is while (x[i] <= y && i <= r), which reads x[i] before checking that i is still in range. When the pivot is at least as large as every key in its range and the range ends at the end of the array, i walks off the end. The fix is to swap the two operands. Output from output/05-legacy-first-pivot.txt:

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.

Nearly half of short random arrays crashed it — 4,680 of 10,000 — and the fixed version was wrong on none. The code, original and fixed side by side, is legacy/FirstPivotQuickSort.java.

The 2015 first-pivot code, with the one-line fix
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);
        }
    }
}

The third post was fine

The 2015 post with quicksort(t, p, r) and a static array was the Lomuto partition with the last element as pivot. It agrees with the clean Lomuto.java on 5,000 random arrays and appears in the 20,000-array agreement test above. Its explanation (the walk-through of [15, 34, 26, 67, 95, 24]) is replaced by the dry-run trace in the Lomuto section above, which is generated by code instead of typed by hand.

The 2015 Lomuto code, logic unchanged
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);
    }
}

Going deeper

What Arrays.sort actually does

Do not ship any of the code above if you can call Arrays.sort. For primitives it is also a Quick Sort, but a far more elaborate one — and the 2015 post’s one-line claim about it deserved checking against the JDK’s own source rather than memory. Read from this JDK’s lib/src.zip by JdkSourceTest.java (output: output/13-jdk-source.txt):

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 <T> void sort(T[] a, Comparator<? super T> 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  }

Three facts follow directly from those lines. Arrays.sort(int[]) calls DualPivotQuicksort, whose class comment credits Vladimir Yaroslavskiy, Jon Bentley and Josh Bloch: two pivots instead of one. Small ranges (up to 44 elements) go to insertion sort. And there is a depth guard: when the recursion gets too deep, the code abandons Quick Sort and calls heapSort, which is the JDK’s answer to the worst case described earlier. The exact depth the guard allows depends on how bits evolves through the method, which I did not trace, so I am not quoting a number. Sorting an object array (sort(Object[])) is a different algorithm entirely: it calls ComparableTimSort.

Going deeper

Should you write Quick Sort yourself?

Almost never in production, and always in an interview. Use Arrays.sort or List.sort: they are tested, they guard against the worst case, and the object version is a different, stable algorithm. Write your own to learn recursion and partitioning, or when an exercise demands it. If you do, the checklist this article produced is short: use Hoare with a middle pivot or Lomuto with a random pivot; use a three-way partition when duplicates are likely; recurse into the smaller side; and test on sorted, reverse-sorted, all-equal and few-distinct-key input, not just on a sample that happens to work.
CaseTimeMeasured here
Average / best (balanced splits)O(n log n)n = 100,000 random: 2,050,086 comparisons (Lomuto), 2,377,190 (Hoare)
Worst (pivot is always the smallest or largest)O(n²)n = 5,000: 12,497,500 comparisons, recursion 5,000 deep
Extra spaceO(log n) stack if you recurse into the smaller side; O(n) otherwisedeepest recursion 2 vs overflow on 100,000 sorted keys

Further reading

No Comments yet!

This site uses Akismet to reduce spam. Learn how your comment data is processed.