Skip to lesson

Quicksort is one of the fastest general-purpose in-place sorting algorithms. It partitions arrays around a pivot element, recursively sorting smaller and larger segments.

Divide and conquer through partitioning

Quick sort picks a pivot, puts smaller elements before it and larger ones after it, then sorts both sides recursively; it takes O(n log n) on average and O(n^2) in the worst case.

While merge sort divides arrays by index and combines them later, quicksort partitions arrays by value. A pivot element is selected from the array. The partition step rearranges elements so all values smaller than the pivot move to the left. All values greater than the pivot move to the right. At the conclusion of the partition step, the pivot sits in its permanent final sorted position!

Why is partitioning so powerful? After partitioning, the pivot never moves again throughout the rest of the algorithm. Quicksort then recursively sorts the left partition and right partition independently. Because partitioning operates directly within the array, quicksort sorts in place with zero auxiliary array buffers.

Consider tracing Lomuto partition on [10, 80, 30, 90, 40, 50, 70] with pivot 70: Index 0 (10): 10 < 70, keep in left boundary. Index 2 (30): 30 < 70, swap with 80: [10, 30, 80, 90, 40, 50, 70]. Index 4 (40): 40 < 70, swap with 80: [10, 30, 40, 90, 80, 50, 70]. Index 5 (50): 50 < 70, swap with 90: [10, 30, 40, 50, 80, 90, 70]. Swap pivot 70 with 80: [10, 30, 40, 50, 70, 90, 80]. Pivot 70 is placed at index 4.

  • Pivot placement: pivot lands in its exact final sorted position in O(n) time.
  • In-place sorting: elements rearrange directly within array bounds without buffer copies.
  • Recursive independence: left and right partitions sort independently.
  1. Choose pivot element.
  2. Initialize boundary index i.
  3. Scan elements from low to high - 1.
  4. If current element < pivot, increment i and swap.
  5. Swap pivot into position i + 1 and return pivot index.

Quick sort: partition around pivot 70

Step 1 of 9

Array: 10, 80, 30, 90, 40, 50, 70. pivot at index 6. store at index 0.
pivot
70
The pivot is the last value, 70. We will move everything smaller than 70 to the front. "store" marks where the next small value goes.

Order of execution

Run one partition

Tap the steps of quick sort in order.

Lomuto versus Hoare partition schemes

Lomuto partition scans left to right with one boundary pointer and uses the last value as pivot. Hoare partition moves two pointers inward from both ends. The examples show both.

Example 1 · Quicksort with Lomuto Partition

QuickSortLomutoDemo.javaJava
import java.util.Arrays;
public class QuickSortLomutoDemo {    public static void quickSort(int[] arr, int low, int high) {        if (low < high) {            int p = partition(arr, low, high);            quickSort(arr, low, p - 1);            quickSort(arr, p + 1, high);        }    }
    private static int partition(int[] arr, int low, int high) {        int pivot = arr[high];        int i = low - 1;        for (int j = low; j < high; j++) {            if (arr[j] <= pivot) {                i++;                int tmp = arr[i];                arr[i] = arr[j];                arr[j] = tmp;            }        }        int tmp = arr[i + 1];        arr[i + 1] = arr[high];        arr[high] = tmp;        return i + 1;    }
    public static void main(String[] args) {        int[] numbers = {10, 80, 30, 90, 40, 50, 70};        quickSort(numbers, 0, numbers.length - 1);        System.out.println(Arrays.toString(numbers));    }}
Output
[10, 30, 40, 50, 70, 80, 90]

What this code does

  • Pivot 70 partitions array into elements <= 70 and > 70.
  • Pivot lands at index 4 and remains fixed.
  • Recursive calls sort left [10, 30, 40, 50] and right [80, 90].

Example 2 · Quicksort with Hoare Partition

QuickSortHoareDemo.javaJava
import java.util.Arrays;
public class QuickSortHoareDemo {    public static void quickSort(int[] arr, int low, int high) {        if (low < high) {            int p = partition(arr, low, high);            quickSort(arr, low, p);            quickSort(arr, p + 1, high);        }    }
    private static int partition(int[] arr, int low, int high) {        int pivot = arr[low];        int i = low - 1;        int j = high + 1;        while (true) {            do { i++; } while (arr[i] < pivot);            do { j--; } while (arr[j] > pivot);            if (i >= j) return j;            int tmp = arr[i];            arr[i] = arr[j];            arr[j] = tmp;        }    }
    public static void main(String[] args) {        int[] numbers = {8, 4, 7, 3, 9, 2, 6};        quickSort(numbers, 0, numbers.length - 1);        System.out.println(Arrays.toString(numbers));    }}
Output
[2, 3, 4, 6, 7, 8, 9]

What this code does

  • Two pointers move inward from low and high until elements violate order.
  • Pointers swap violating elements and continue.
  • Hoare partition performs fewer swaps than Lomuto.

Lomuto partition uses the last element as pivot and scans forward with a single boundary pointer. It is easier to understand and implement, but performs more swaps when elements are already ordered. Hoare partition uses two pointers starting at opposite ends of the array and advancing inward toward each other. The left pointer advances until finding an element greater than or equal to the pivot. The right pointer advances until finding an element smaller than or equal to the pivot. When both pointers stop, they swap their elements and continue until they cross. Hoare partitioning executes roughly three times fewer swaps on average compared to Lomuto. However, Hoare partition does not place the pivot at the returned index. Instead, it splits the array into two partitions [low..j] and [j+1..high] for recursive sorting. Both partitioning schemes run in linear O(n) time.

  • Lomuto scheme: single-direction scan, places pivot at exact boundary, easier to code.
  • Hoare scheme: bidirectional inward scan, three times fewer swaps, faster in practice.
  • Partition cost: exactly O(n) comparisons in a single linear sweep for both schemes.

Worst-case O(n²) and randomized pivot selection

Quick sort slows to O(n²) when the pivot is always the smallest or largest value. A random pivot avoids this on sorted input. The program below sorts an already sorted array safely.

Example 3 · Randomized Quicksort Avoiding Worst-Case

RandomizedQuickSortDemo.javaJava
import java.util.Arrays;import java.util.Random;
public class RandomizedQuickSortDemo {    private static final Random rand = new Random(42);
    public static void quickSort(int[] arr, int low, int high) {        if (low < high) {            int p = randomizedPartition(arr, low, high);            quickSort(arr, low, p - 1);            quickSort(arr, p + 1, high);        }    }
    private static int randomizedPartition(int[] arr, int low, int high) {        int r = low + rand.nextInt(high - low + 1);        int tmp = arr[r];        arr[r] = arr[high];        arr[high] = tmp;        return partition(arr, low, high);    }
    private static int partition(int[] arr, int low, int high) {        int pivot = arr[high];        int i = low - 1;        for (int j = low; j < high; j++) {            if (arr[j] <= pivot) {                i++;                int t = arr[i];                arr[i] = arr[j];                arr[j] = t;            }        }        int t = arr[i + 1];        arr[i + 1] = arr[high];        arr[high] = t;        return i + 1;    }
    public static void main(String[] args) {        int[] sorted = {1, 2, 3, 4, 5, 6, 7, 8};        quickSort(sorted, 0, sorted.length - 1);        System.out.println("Sorted: " + Arrays.toString(sorted));    }}
Output
Sorted: [1, 2, 3, 4, 5, 6, 7, 8]

What this code does

  • Random index swapped with high ensures random pivot selection.
  • Already sorted arrays avoid O(n²) degradation.
  • Guarantees O(n log n) expected time on all input arrays.

If the chosen pivot is consistently the smallest or largest element, the partition is extremely unbalanced. One partition receives 0 elements while the other receives n - 1 elements. This causes the recursion tree depth to grow from log₂(n) to n, resulting in slow O(n²) performance. This worst case happens on already sorted arrays when choosing the first or last element as pivot. How do we prevent this worst-case degradation? Randomized quicksort picks a random index between low and high. It swaps it with the pivot before partitioning. Because every element has equal probability of being chosen, the expected partition split remains balanced. Randomized quicksort guarantees average O(n log n) performance on every input distribution. Modern production libraries also use the median-of-three heuristic. They inspect the first, middle, and last elements and choose their median value as pivot. This virtually eliminates worst-case behavior on sorted and reverse-sorted arrays.

  • Worst-case trigger: consistently choosing minimum or maximum element as pivot.
  • Randomized pivot: pick a random index to guarantee O(n log n) expected time on all inputs.
  • Median of three: inspect first, middle, and last elements to pick a robust pivot.

Predict the output

Predict the split

Read each snippet and pick what it prints (smaller values, larger values).

Round 1 of 2

int[] e = {1, 2, 3, 4, 5};
int pivot = e[e.length - 1];
int smaller = 0;
for (int v : e) {
if (v < pivot) smaller++;
}
System.out.println(smaller + " " + (e.length - 1 - smaller));

Next step

Check your understanding

10 quick questions