M13 · Sorting

Quicksort and Partitioning

Quicksort picks a pivot, partitions the range so that smaller elements come before it and the rest after it, and recurses on both sides. The pivot lands in its final place after every partition. It sorts in place and is fast on average, but a bad pivot sequence makes it quadratic. This lesson uses the Lomuto partition with the middle element as pivot and shows exactly where that choice helps and where it fails.

~45 minIntermediateC# · Python · Java · C++
Curriculum: M13 Sorting · 5 of 5 lessons available

You will be able to

  • Trace the Lomuto partition and state its invariant: items[low..i) < pivot ≤ items[i..j).
  • Explain why the pivot is in its final position after each partition and why that makes the recursion correct.
  • Derive O(n log n) for balanced splits and O(n²) for maximally unbalanced ones, including stack depth.
  • Explain the trade-offs of first, last, middle, median-of-three and random pivots, and why many equal keys hurt Lomuto.
  • Describe how introsort and three-way partitioning make library sorts safe, and why quicksort is not stable.

Helpful before this lesson

  • M03 Big O — Count operations, describe growth, and tell worst-case, average and amortized costs apart.
  • M05 Arrays — Contiguous storage, index arithmetic, and how a dynamic array grows while keeping append cheap.
  • M11 Recursion — Base cases, the call stack, recursion trees and the first look at memoization.

Guidance only. Those modules are planned; the essentials are recapped here.

Visual walkthrough

The interactive visualizer needs JavaScript. The explanation and all four implementations below work without it.

Mental model

Merge sort does the easy part first (split in the middle) and the hard part last (merge). Quicksort does it the other way round: the hard part first (partition), and then nothing is left to combine.

  1. Pick a pivot value from the range.
  2. Partition: rearrange the range so that everything smaller than the pivot comes first, then the pivot, then everything else. The pivot is now exactly where it will be in the sorted array.
  3. Recurse on the left part and on the right part. A range of zero or one element is done.

When both recursive calls return, the whole range is sorted: the left part is sorted and smaller than the pivot, the right part is sorted and not smaller, and the pivot is between them.

This implementation

The lab and the four listings use one precise version, so every step is reproducible:

  • Bounds: sortRange(low, high) sorts items[low..high], both inclusive. The first call is sortRange(0, n − 1); low ≥ high (zero or one element) is the base case.
  • Pivot rule: the middle element, index low + (high − low) / 2 (rounding down, written so that low + high cannot overflow). It is swapped to index high and stays there during the partition.
  • Partition scheme: Lomuto. One index j scans low..high−1; a second index i marks the end of the "smaller than pivot" part.
  • Recursion: left part first, then right part, both recursively.

The Lomuto partition

pivot = items[high]            (after parking the middle element there)
i = low
for j in low .. high − 1:
    if items[j] < pivot:
        swap items[i], items[j]
        i = i + 1
swap items[i], items[high]     (the pivot moves to its final place)
return i

Invariant, true before every iteration of the loop:

low        i          j          high
 [  < pivot  |  ≥ pivot  |  unseen  | pivot ]

When items[j] is smaller than the pivot, swapping it with items[i] (the first "≥ pivot" element) and advancing i extends the left part by one. Otherwise j just moves on, which extends the right part. When j reaches high, the unseen part is empty, and swapping the pivot into slot i puts it between the two parts. In the lab, the tags < p and ≥ p show the two regions growing, and the pins mark i and j.

Sometimes i = j and the swap exchanges an element with itself. That is harmless; the Swaps metric counts it, because the code executes it.

The recursion stack

The brackets in front of the array in the lab are the active sortRange calls, outermost at the back, innermost (bright) at the front. The text panel lists them too. Two things to notice:

  • Calls on empty ranges (low > high) happen whenever the pivot lands at the edge of its range. They return immediately but still cost a call.
  • The depth depends on how balanced the splits are. That is the whole story of quicksort's performance.

Cost

Each partition of m elements makes m − 1 comparisons. What matters is how the partitions nest.

Balanced splits. If the pivot always lands near the middle, every level of recursion partitions about n elements in total, and there are about log₂ n levels: Θ(n log n) comparisons and Θ(log n) stack depth. The Already sorted preset is this case for the middle pivot: 15 sorted values split into 7 and 7, then 3 and 3, then 1 and 1.

Unbalanced splits. If the pivot is always the smallest or largest value, one side is empty and the other has m − 1 elements: (n − 1) + (n − 2) + … + 1 = n(n − 1)/2 comparisons, Θ(n²), and the stack grows to n frames.

Average. For random input (or a random pivot) the expected number of comparisons is about 2n ln n ≈ 1.39 n log₂ n. That is more comparisons than merge sort, but quicksort moves fewer elements, works in place and scans memory sequentially, which is why tuned quicksorts are fast in practice.

Measure Best / average Worst
Comparisons Θ(n log n) n(n − 1)/2
Extra space (stack) Θ(log n) Θ(n) with this recursion
Stable no no

Choosing the pivot

The pivot rule decides which inputs are slow. Every deterministic rule has some bad input; the question is whether that input is likely.

  • First or last element: sorted and reversed input, which are common in practice, are the worst case. Avoid.
  • Middle element (this lesson): sorted and reversed input split perfectly. Bad inputs still exist; they are just unlikely by accident. An attacker who knows the rule can construct one.
  • Median of three (first, middle, last): better splits on typical data, still deterministic.
  • Random pivot: no fixed input is bad; the expected cost is O(n log n) for every input. The trace would no longer be reproducible from the input alone, which is why this lab does not use it.

Lomuto's weakness: equal keys

Run the All equal preset. With every key equal, no element is strictly smaller than the pivot, so i never moves, the pivot lands at low, and the right part has every remaining element. That is the unbalanced case: n(n − 1)/2 comparisons and stack depth n, for an input that is already sorted. Arrays with many duplicates come close to this.

Two standard fixes:

  • Hoare's partition (the original 1962 scheme) moves two indices toward each other and stops both on elements equal to the pivot, so runs of equal keys are split roughly in half. It also makes fewer swaps than Lomuto. It is harder to get right: the pivot does not necessarily end up in its final slot, and the recursion uses [low, p] and [p + 1, high].
  • Three-way partitioning (Dijkstra's "Dutch national flag") splits the range into < pivot, = pivot and > pivot and recurses only on the outer two. All-equal input then takes one pass.

Keeping the stack small

Recursing on both sides can use Θ(n) stack in the worst case, enough to overflow on large inputs (Python's default recursion limit is about 1,000). The fix is simple: recurse on the smaller part and loop on the larger one. The smaller part is at most half the range, so the depth is at most log₂ n, whatever the pivots. The teaching version keeps both calls recursive so the lab can show the left-then-right order clearly.

What libraries do

No mainstream library ships plain quicksort; they all guard against its worst case:

  • C++ std::sort must make O(n log n) comparisons since C++11. libstdc++ and libc++ use introsort: quicksort that switches to heap sort when the recursion gets too deep (about 2 log₂ n), and insertion sort for small ranges.
  • C# Array.Sort / List<T>.Sort: also an introspective sort (quicksort, heap sort fallback, insertion sort), documented as unstable.
  • Java Arrays.sort for primitives: a dual-pivot quicksort (two pivots, three parts). Object arrays use TimSort instead, because objects need a stable sort.
  • Python does not use quicksort at all: list.sort is Timsort, stable and adaptive.

Not stable

Run the Not stable preset: 2a 2b 1. The middle element 2b is parked at the end as pivot, 1 is swapped to the front, and the pivot swap puts 2b at index 1 and 2a at index 2: 1 2b 2a. Partition swaps jump elements over equal ones. If you need stability, use merge sort or your language's stable sort.

The teaching implementation

Quicksort.Sort / quicksort takes a comparison (or a key in Python) and follows the exact rules above. The C++ version uses signed indices so that the empty range [low, low − 1] needs no special case. Because quicksort is unstable, the shared fixture records the exact order this implementation leaves equal keys in (all-equal 4a 4b 4c 4d becomes 4b 4c 4a 4d), and all four languages must reproduce it; each is also compared with its built-in sort on 500 random inputs.

Common mistakes

  • (low + high) / 2 in fixed-width integers: overflows for huge arrays. Use low + (high − low) / 2.
  • Recursing on [low, p] with Lomuto: the pivot is already placed; including it can recurse forever on a two-element range.
  • First-element pivot on sorted data: quadratic time and a stack overflow on large inputs.
  • <= in the Lomuto comparison: still correct, but now equal keys all go left and the all-equal case is just as bad, mirrored.
  • Assuming the library sort is quicksort and therefore unstable or quadratic: check the documented contract instead.

Worked practice

1. Partition [7, 2, 9, 4, 5] with this lesson's rules. Where does the pivot end up?

Answer

The middle index is 2, value 9; it is swapped to the end: [7, 2, 5, 4, 9]. Every other value is smaller than 9, so each one is "swapped" with itself and i reaches 4. The final swap leaves 9 at index 4, its sorted position. The left part [7, 2, 5, 4] holds everything else and the right part is empty: an unbalanced split, even though the input was not sorted.

2. With the middle pivot, how deep does the stack get on 15 sorted values?

Answer

4 frames. The range sizes are 15, 7, 3 and 1: each pivot is the true median, so every split is perfect (the one-element calls are the base case at depth 4).

3. Why does random pivot selection make quicksort's worst case unlikely but not impossible?

Answer

Every run can still pick the smallest element by chance at every level, so n(n − 1)/2 comparisons remain possible. But the probability of consistently bad pivots falls off extremely fast, and no particular input triggers it: the expected cost is O(n log n) for every input.

Summary

  • Quicksort partitions around a pivot, which lands in its final place, then recurses on both sides.
  • Lomuto: items[low..i) < pivot ≤ items[i..j); simple, but quadratic on many equal keys.
  • Balanced splits give Θ(n log n) and Θ(log n) stack; unbalanced ones give Θ(n²) and Θ(n) stack.
  • The middle pivot handles sorted input; random pivots, three-way partitioning and introsort make production sorts robust.
  • In place, fast in practice, not stable.

Full implementation

Quicksort (Lomuto, middle pivot) in four languages, each checked against one shared fixture that pins down the exact (unstable) order of equal keys, and 500 random inputs whose keys are compared with the language's built-in sort.

namespace Bekadan.Dsa.Examples.Sorting;
 
/// <summary>
/// Quicksort with the Lomuto partition and the middle element as pivot.
/// In place, not stable. O(n log n) comparisons on average and on sorted
/// input; O(n²) in the worst case (for example, all keys equal).
/// Recursion depth is O(log n) for balanced splits and up to n in the worst case.
/// </summary>
public static class Quicksort
{
    public static void Sort<T>(T[] items, Comparison<T> compare) => SortRange(items, 0, items.Length - 1, compare);
 
    /// <summary>Sorts items[low..high] (both inclusive).</summary>
    private static void SortRange<T>(T[] items, int low, int high, Comparison<T> compare)
    {
        if (low >= high)
            return; // zero or one element
        int p = Partition(items, low, high, compare);
        SortRange(items, low, p - 1, compare);
        SortRange(items, p + 1, high, compare);
    }
 
    /// <summary>Returns the pivot's final index p: items[low..p) &lt; pivot &lt;= items(p..high].</summary>
    private static int Partition<T>(T[] items, int low, int high, Comparison<T> compare)
    {
        int mid = low + (high - low) / 2;
        (items[mid], items[high]) = (items[high], items[mid]); // park the middle element at the end
        T pivot = items[high];
        int i = low; // items[low..i) < pivot
        for (int j = low; j < high; j++)
        {
            if (compare(items[j], pivot) < 0)
            {
                (items[i], items[j]) = (items[j], items[i]);
                i++;
            }
        }
        (items[i], items[high]) = (items[high], items[i]); // the pivot lands in its final place
        return i;
    }
}

Tested on .NET 10 (SDK 10.0.403), C# 14 · examples/csharp/Bekadan.Dsa.Examples/Sorting/Quicksort.cs

"""Quicksort with the Lomuto partition and the middle element as pivot.
 
In place, not stable. O(n log n) comparisons on average and on sorted input;
O(n^2) in the worst case (for example, all keys equal). The recursion depth
is O(log n) for balanced splits but can reach n, past Python's default
recursion limit for large worst-case inputs.
"""
 
from collections.abc import Callable
from typing import Any
 
 
def _identity(item: Any) -> Any:
    return item
 
 
def quicksort(items: list[Any], key: Callable[[Any], Any] = _identity) -> None:
    _sort_range(items, 0, len(items) - 1, key)
 
 
def _sort_range(items: list[Any], low: int, high: int, key: Callable[[Any], Any]) -> None:
    """Sorts items[low..high], both inclusive."""
    if low >= high:
        return  # zero or one element
    p = _partition(items, low, high, key)
    _sort_range(items, low, p - 1, key)
    _sort_range(items, p + 1, high, key)
 
 
def _partition(items: list[Any], low: int, high: int, key: Callable[[Any], Any]) -> int:
    """Returns the pivot's final index p: items[low:p] < pivot <= items[p + 1:high + 1]."""
    mid = low + (high - low) // 2
    items[mid], items[high] = items[high], items[mid]  # park the middle element at the end
    pivot = key(items[high])
    i = low  # items[low:i] < pivot
    for j in range(low, high):
        if key(items[j]) < pivot:
            items[i], items[j] = items[j], items[i]
            i += 1
    items[i], items[high] = items[high], items[i]  # the pivot lands in its final place
    return i

Tested on CPython 3.14.0 · examples/python/dsa_examples/quicksort.py

package dev.bekadan.dsa.sorting;
 
import java.util.Comparator;
 
/**
 * Quicksort with the Lomuto partition and the middle element as pivot.
 * In place, not stable. O(n log n) comparisons on average and on sorted
 * input; O(n^2) in the worst case (for example, all keys equal).
 * Recursion depth is O(log n) for balanced splits and up to n in the worst case.
 */
public final class Quicksort {
    private Quicksort() {
    }
 
    public static <T> void sort(T[] items, Comparator<? super T> comparator) {
        sortRange(items, 0, items.length - 1, comparator);
    }
 
    /** Sorts items[low..high] (both inclusive). */
    private static <T> void sortRange(T[] items, int low, int high, Comparator<? super T> comparator) {
        if (low >= high) {
            return; // zero or one element
        }
        int p = partition(items, low, high, comparator);
        sortRange(items, low, p - 1, comparator);
        sortRange(items, p + 1, high, comparator);
    }
 
    /** Returns the pivot's final index p: items[low..p) &lt; pivot &lt;= items(p..high]. */
    private static <T> int partition(T[] items, int low, int high, Comparator<? super T> comparator) {
        int mid = low + (high - low) / 2;
        swap(items, mid, high); // park the middle element at the end
        T pivot = items[high];
        int i = low; // items[low..i) < pivot
        for (int j = low; j < high; j++) {
            if (comparator.compare(items[j], pivot) < 0) {
                swap(items, i, j);
                i++;
            }
        }
        swap(items, i, high); // the pivot lands in its final place
        return i;
    }
 
    private static <T> void swap(T[] items, int a, int b) {
        T tmp = items[a];
        items[a] = items[b];
        items[b] = tmp;
    }
}

Tested on Java 25 (Temurin 25.0.5); also compiles on Java 17 · examples/java/src/main/java/dev/bekadan/dsa/sorting/Quicksort.java

#pragma once
 
#include <cstddef>
#include <functional>
#include <span>
#include <utility>
 
namespace bekadan::dsa {
 
// Quicksort with the Lomuto partition and the middle element as pivot.
// In place, not stable. O(n log n) comparisons on average and on sorted
// input; O(n^2) in the worst case (for example, all keys equal).
// Recursion depth is O(log n) for balanced splits and up to n in the worst case.
// Indices are signed so that an empty range [low, low - 1] needs no special case.
 
namespace detail {
 
// Returns the pivot's final index p: items[low..p) < pivot <= items(p..high].
template <typename T, typename Less>
std::ptrdiff_t lomuto_partition(std::span<T> items, std::ptrdiff_t low, std::ptrdiff_t high, Less& less) {
    const auto at = [&](std::ptrdiff_t k) -> T& { return items[static_cast<std::size_t>(k)]; };
    const std::ptrdiff_t mid = low + (high - low) / 2;
    std::swap(at(mid), at(high));  // park the middle element at the end
    const T& pivot = at(high);     // stays at high until the final swap
    std::ptrdiff_t i = low;        // items[low..i) < pivot
    for (std::ptrdiff_t j = low; j < high; ++j) {
        if (less(at(j), pivot)) {
            std::swap(at(i), at(j));
            ++i;
        }
    }
    std::swap(at(i), at(high));  // the pivot lands in its final place
    return i;
}
 
// Sorts items[low..high] (both inclusive).
template <typename T, typename Less>
void quicksort_range(std::span<T> items, std::ptrdiff_t low, std::ptrdiff_t high, Less& less) {
    if (low >= high)
        return;  // zero or one element
    const std::ptrdiff_t p = lomuto_partition(items, low, high, less);
    quicksort_range(items, low, p - 1, less);
    quicksort_range(items, p + 1, high, less);
}
 
}  // namespace detail
 
template <typename T, typename Less = std::less<>>
void quicksort(std::span<T> items, Less less = {}) {
    detail::quicksort_range(items, 0, static_cast<std::ptrdiff_t>(items.size()) - 1, less);
}
 
}  // namespace bekadan::dsa

Tested on C++23, GCC 15.3 (libstdc++) · examples/cpp/include/bekadan/dsa/quicksort.hpp

References