Lesson 36 · Core algorithms

Quick Sort

Pick a pivot, partition the array so smaller values sit to its left and larger ones to its right, then sort each side the same way. The pivot decides the cost.

Quick Sort concept diagramA visual explanation of the layout and operations shown in this lesson.choose a pivot, then move smaller values left and larger values right3145798all < 5all > 5pivotfinal placethe pivot never moves again; recurse on the two sidesa bad pivot splits 1 and n−1 — that is the O(n²) worst case
1

How Quick Sort Works

  1. If the range has 0 or 1 values, it is sorted: stop
  2. Choose one value as the pivot
  3. Partition: move values ≤ pivot to its left and larger values to its right
  4. The pivot is now in its final position
  5. Sort the left part and the right part the same way

Quick sort is a divide and conquer sort that does all its work while dividing. After one partition the pivot sits exactly where it will be in the sorted array, every value to its left is smaller or equal and every value to its right is larger. No value ever has to cross the pivot again, so the two sides are independent problems.

On [7, 2, 9, 4, 5] with pivot 5, one pass of 4 comparisons gives [2, 4, 5, 7, 9]. The 5 is final. Sorting [2, 4] and [7, 9] costs one comparison each, and once both sides are sorted the whole array is sorted. There is no merge step, which is the opposite of merge sort: merge sort splits without looking and does its work when combining.

  • Quick sort is not stable: a long swap can carry a value past an equal one
  • It sorts in place, needing only the recursion stack, which is why it is usually faster than merge sort on arrays in memory
2

Lomuto and Hoare Partition

Lomuto partition takes the last value as the pivot and scans left to right with j, keeping a boundary i. Everything at lo..i is ≤ pivot and everything at i+1..j−1 is larger. When a[j] <= pivot, the boundary grows by one and a[j] is swapped into it. After the scan, the pivot is swapped into i + 1, between the two regions. It is short and easy to prove, which is why textbooks use it.

Hoare partition starts two indexes at the ends. The left one moves right until it finds a value ≥ pivot, the right one moves left until it finds a value ≤ pivot, and the pair is swapped. It stops when they cross. It does about a third as many swaps on random input and splits runs of equal keys evenly, but it does not leave the pivot at the returned index, so the recursive calls are (lo, p) and (p + 1, hi), not p − 1.

The two classic partition schemes
LomutoHoare
Pivotlast valueusually the first or middle value
Swaps on random inputmoreabout 3× fewer
All values equalsplit n − 1 | 0: O(n²)split near the middle: O(n log n)
Returned indexthe pivot's final placea split point only
  • Lomuto with < instead of <= is also correct; it only changes which side equal values land on
  • Mixing the two, Hoare's loop with Lomuto's (lo, p − 1) calls, drops values from the recursion and leaves the array unsorted
3

Quick Sort Time Complexity

One partition of a range of n values compares each of them with the pivot once, so it costs O(n). If the pivot lands near the middle every time, the range halves on each level, there are about log₂ n levels and the total is O(n log n). On random input the average is about 1.39 n log₂ n comparisons, a little more than merge sort, but each one is cheap and touches memory in order.

  • Time complexity: best O(n log n), average O(n log n), worst O(n²)
  • Space complexity: O(log n) stack on average, O(n) in the worst case unless the smaller side is recursed first

If the pivot is the smallest or largest value every time, each partition peels off one value. There are n levels instead of log n, and the comparisons add up to (n − 1) + (n − 2) + … + 1 = n(n − 1)/2, which is O(n²). For a million values that is about 500 billion comparisons instead of about 20 million.

The worst case is not exotic. With the last value as pivot, an array that is already sorted produces it exactly: every pivot is the maximum, every split is n − 1 against 0. Reverse-sorted input does the same with a first-value pivot.

  • Recurse into the smaller side and loop on the larger one; the stack then never goes deeper than log₂ n frames, even when the time is quadratic
  • Below about 16 values, switching to insertion sort is faster than more partitioning
Key reference

Terms, operations, and practical uses

Core ideas

  • PivotThe value the range is partitioned around. After partitioning it sits in its final sorted position.
  • PartitionOne linear pass that puts values ≤ pivot on one side and larger values on the other, in place.
  • No combine stepOnce both sides are sorted the whole range is sorted, because no value is on the wrong side of the pivot.

Properties

  • In placeOnly swaps inside the array; the extra memory is the recursion stack, O(log n) when the smaller side is recursed first.
  • Not stableLong-distance swaps can move a value past an equal one, so equal keys may change order.
  • Average 1.39 n log₂ n comparisonsSlightly more comparisons than merge sort, but cheap ones on contiguous memory, so it is usually faster.

Costs and fixes

  • Worst case O(n²)When every pivot is the smallest or largest value, for example a last-value pivot on sorted input.
  • Random or median-of-three pivotMakes the worst case depend on luck instead of on the input's order.
  • Three-way partitionGroups values equal to the pivot so arrays with many duplicates stay O(n log n), and all-equal arrays take O(n).
Implementation

Code in Python, C++ and Java

def quick_sort(values, lo=0, hi=None):
    if hi is None:
        hi = len(values) - 1
    if lo < hi:
        p = partition(values, lo, hi)
        quick_sort(values, lo, p - 1)     # the pivot itself is excluded
        quick_sort(values, p + 1, hi)
    return values


def partition(values, lo, hi):
    pivot = values[hi]                    # Lomuto: last element is the pivot
    i = lo - 1                            # boundary of the "smaller" region
    for j in range(lo, hi):
        if values[j] <= pivot:
            i += 1
            values[i], values[j] = values[j], values[i]
    values[i + 1], values[hi] = values[hi], values[i + 1]
    return i + 1                          # the pivot's final index


print(quick_sort([7, 2, 9, 4, 5]))
#include <iostream>
#include <vector>

int partition(std::vector<int>& values, int lo, int hi) {
    const int pivot = values[hi];         // Lomuto: last element is the pivot
    int i = lo - 1;                       // boundary of the "smaller" region
    for (int j = lo; j < hi; ++j) {
        if (values[j] <= pivot) std::swap(values[++i], values[j]);
    }
    std::swap(values[i + 1], values[hi]);
    return i + 1;                         // the pivot's final index
}

void quickSort(std::vector<int>& values, int lo, int hi) {
    if (lo < hi) {
        const int p = partition(values, lo, hi);
        quickSort(values, lo, p - 1);     // the pivot itself is excluded
        quickSort(values, p + 1, hi);
    }
}

int main() {
    std::vector<int> values{7, 2, 9, 4, 5};
    quickSort(values, 0, static_cast<int>(values.size()) - 1);
    std::cout << '[';
    for (size_t k = 0; k < values.size(); ++k) std::cout << (k ? ", " : "") << values[k];
    std::cout << "]\n";
}
import java.util.Arrays;

public class Main {
    static int partition(int[] values, int lo, int hi) {
        int pivot = values[hi];           // Lomuto: last element is the pivot
        int i = lo - 1;                   // boundary of the "smaller" region
        for (int j = lo; j < hi; j++) {
            if (values[j] <= pivot) {
                i++;
                int tmp = values[i];
                values[i] = values[j];
                values[j] = tmp;
            }
        }
        int tmp = values[i + 1];
        values[i + 1] = values[hi];
        values[hi] = tmp;
        return i + 1;                     // the pivot's final index
    }

    static void quickSort(int[] values, int lo, int hi) {
        if (lo < hi) {
            int p = partition(values, lo, hi);
            quickSort(values, lo, p - 1); // the pivot itself is excluded
            quickSort(values, p + 1, hi);
        }
    }

    public static void main(String[] args) {
        int[] values = {7, 2, 9, 4, 5};
        quickSort(values, 0, values.length - 1);
        System.out.println(Arrays.toString(values));
    }
}
Watch it run

Step through it

Running on [7, 2, 9, 4, 5]

partition [7, 2, 9, 4, 5], pivot = 5array72945i = −1jpivot≤ part is empty, > part is emptypartitioncomparisons0swaps0i (end of ≤ part)-1j (scanning)0
Step 1

Choose the pivot

Lomuto takes the last value, 5, as the pivot. The boundary i starts at −1, one before the range, because no value is known to be ≤ 5 yet. j will scan indexes 0 to 3.

Output
1 / 14
4

Choosing the Pivot

Randomized quick sort picks the pivot at a random position. No fixed input is then bad: sorted, reversed or crafted arrays all take O(n log n) expected time, and the chance of anything near n² comparisons is tiny. Median of three takes the median of the first, middle and last values, which fixes sorted and reversed input cheaply but can still be defeated by a crafted array.

Libraries go one step further. Introsort, used by C++ std::sort, runs quick sort but counts the recursion depth; past about 2 log₂ n levels it switches that range to heap sort, so the worst case is O(n log n). Java sorts primitive arrays with a dual-pivot quick sort. Python does not use quick sort at all; its sorted is Timsort, a stable merge-based sort.

What each pivot rule costs
Pivot ruleSorted inputCrafted bad input
First or last valueO(n²)O(n²)
Median of threeO(n log n)O(n²), possible
Random positionO(n log n) expectedO(n log n) expected
IntrosortO(n log n)O(n log n)
  • A random pivot needs a decent random source; a fixed seed lets an attacker rebuild the bad input
  • Swap the chosen pivot to the end first, and the Lomuto loop works unchanged
5

Duplicates and Three-Way Partitioning

Many equal keys are the other way to reach O(n²). With Lomuto and <=, an array of equal values puts every value on the left, the pivot lands at the end, and each call removes one value, exactly like sorted input.

Three-way partitioning splits the range into < pivot, = pivot and > pivot, then recurses only on the two outer parts. The equal block is finished in one pass, so an array of identical values sorts in O(n). It is the Dutch national flag problem: see sort colors.

The same partition also finds a single order statistic. Quickselect partitions once and then recurses only into the side that holds position k, so it finds the kth smallest value in O(n) average time: see kth largest element in an array.

  • Test every quick sort on sorted, reversed and all-equal arrays; those three expose each slow case
  • Hoare's scheme stops on values equal to the pivot from both sides, so it also splits equal runs evenly