Lesson 4 · Core algorithms

Quickselect

Quickselect finds the value that would sit at position k if the array were sorted, without sorting it. It partitions the array around a pivot like quick sort, sees which side position k falls on, and throws the other side away. Each round works on a smaller piece, so the average cost is linear.

Quickselect concept diagramFive rows of segments for an array of 16 values: one segment of 16, two of 8, four of 4, eight of 2 and sixteen of 1. Quick sort partitions every segment, so each row costs 16 steps. Quickselect partitions only the highlighted segment that contains index k in each row, costing 16, 8, 4 and 2, under 32 in total, compared with about 64 for quick sort.16 values, ideal pivotsquick sortquickselect1616168816844441642222222216200k6430every level costs n: n log n · one segment per level: n + n/2 + n/4 + … < 2n
1

Selecting Without Sorting

Many questions ask for one position of the sorted order: the median, the 10th smallest score, the 100th largest file. Sorting answers them in O(n log n), but it orders every value when only one position matters. The quickselect algorithm, invented by Tony Hoare alongside quick sort, answers the question in O(n) average time.

It rests on one fact about partitioning. Pick a pivot, move every smaller value to its left and every larger value to its right, and the pivot lands at index p, exactly where it would be in the sorted array. Nothing else is in order yet, but you now know which side position k is on.

Positions are counted from 0 here. The k-th smallest (counting from 1) is at index k − 1, and the k-th largest is at index n − k. Converting once at the start avoids the most common off-by-one bug.

  • Input: an array and a target index k
  • Output: the value that would be at index k after sorting
  • Changes the array in place; copy it first if the caller needs the original order
2

The Steps

  1. Check that 0 ≤ k < n, then set lo = 0 and hi = n − 1
  2. While lo < hi, choose a pivot in lo..hi and partition that range; the pivot ends at index p
  3. If p equals k, return a[k]
  4. If k < p, set hi = p − 1; otherwise set lo = p + 1
  5. When the loop ends, return a[k]

On [3, 7, 6, 1, 8, 2, 9, 5, 4] with k = 4, the median: the first pivot, 4, lands at index 3, so the left four values are dropped. In the range 4..8 the pivot 7 lands at index 6, so the right side is dropped. In the range 4..5 the pivot 5 lands at index 4, which is k. The answer is 5 after 8 + 4 + 1 = 13 comparisons, and the values left of it, 3 1 2 4, were never sorted.

Any correct partition works. The tracer uses the simple last-value scheme described in quick sort; a scheme with two inward scans makes fewer swaps. The loop above is iterative, so there is no recursion depth to worry about.

  • Only one side is ever kept, so a loop replaces recursion
  • Each round fixes one more value in its final position
  • The range shrinks every round, so the loop always ends
3

Quickselect Time Complexity

The running time of quickselect depends on how evenly the pivots split the range. If each pivot lands near the middle, the rounds cost about n, n/2, n/4 and so on. That series adds up to less than 2n, so the work is O(n). With a random pivot the split is not always even, but the expected total for the median is still about 3.4n comparisons: linear.

The worst case is O(n²). If every pivot is the smallest or largest value in its range, each round removes only that one value, and the rounds cost n − 1, n − 2, n − 3 and so on. A last-value pivot on input that is already sorted does exactly this. A random pivot, or the median of the first, middle and last values, removes that pattern; a sorted 1..9 then finishes in one round.

The median of medians method chooses a pivot that is guaranteed to split well: cut the array into groups of 5, take each group's median, and recursively select the median of those. It makes quickselect O(n) in the worst case, but the constant is large, so libraries use random or sampled pivots instead. Extra space is O(1) for the loop version.

  • Average O(n); worst case O(n²); O(1) extra space
  • Random pivot: expected O(n) on every input, whatever its order
  • Median of medians: O(n) worst case, slower in practice
Key reference

Terms, operations, and practical uses

Key terms

  • Order statisticThe value at a given index of the sorted order, such as the minimum, median or k-th smallest.
  • PartitionRearranging a range so smaller values are left of the pivot and larger values right of it.
  • Pivot index pWhere the pivot lands after partitioning: its final sorted position.
  • Three-way partitionSplitting into less than, equal to and greater than the pivot in one pass.
Implementation

Code in Python, C++ and Java

def partition(a, lo, hi):
    pivot, store = a[hi], lo
    for j in range(lo, hi):
        if a[j] < pivot:
            a[store], a[j] = a[j], a[store]
            store += 1
    a[store], a[hi] = a[hi], a[store]
    return store, hi - lo


def quickselect(a, k, median3=False, trace=False):
    if not 0 <= k < len(a):
        raise IndexError("k out of range")
    lo, hi, comparisons, rnd = 0, len(a) - 1, 0, 0
    while lo < hi:
        if median3:
            mid = (lo + hi) // 2
            m = sorted([lo, mid, hi], key=lambda i: a[i])[1]
            a[m], a[hi] = a[hi], a[m]
        p, used = partition(a, lo, hi)
        comparisons += used
        rnd += 1
        if trace:
            print(f"round {rnd}: pivot {a[p]} -> index {p} | {a}")
        if p == k:
            break
        if k < p:
            hi = p - 1
        else:
            lo = p + 1
    return a[k], comparisons


a = [3, 7, 6, 1, 8, 2, 9, 5, 4]
value, cost = quickselect(a, 4, trace=True)
print(f"5th smallest: {value} ({cost} comparisons)")
print("5 smallest:", a[:5])

print("sorted, last pivot:", quickselect(list(range(1, 10)), 4)[1], "comparisons")
print("sorted, median of three:", quickselect(list(range(1, 10)), 4, median3=True)[1], "comparisons")

b = [3, 7, 6, 1, 8, 2, 9, 5, 4]
print("2nd largest:", quickselect(b, len(b) - 2)[0])
print("n = 1:", quickselect([42], 0)[0])
try:
    quickselect([3, 7, 6], 5)
except IndexError:
    print("k = 5 on 3 values: rejected")
#include <algorithm>
#include <iostream>
#include <stdexcept>
#include <vector>
using namespace std;

string show(const vector<int>& a, size_t n) {
    string s = "[";
    for (size_t i = 0; i < n; i++) s += (i ? ", " : "") + to_string(a[i]);
    return s + "]";
}

pair<int, int> partitionRange(vector<int>& a, int lo, int hi) {
    int pivot = a[hi], store = lo;
    for (int j = lo; j < hi; j++)
        if (a[j] < pivot) swap(a[store++], a[j]);
    swap(a[store], a[hi]);
    return {store, hi - lo};
}

pair<int, int> quickselect(vector<int>& a, int k, bool median3 = false, bool trace = false) {
    if (k < 0 || k >= (int)a.size()) throw out_of_range("k out of range");
    int lo = 0, hi = a.size() - 1, comparisons = 0, rnd = 0;
    while (lo < hi) {
        if (median3) {
            int mid = (lo + hi) / 2;
            vector<int> idx = {lo, mid, hi};
            sort(idx.begin(), idx.end(), [&](int x, int y) { return a[x] < a[y]; });
            swap(a[idx[1]], a[hi]);
        }
        auto [p, used] = partitionRange(a, lo, hi);
        comparisons += used;
        rnd++;
        if (trace) cout << "round " << rnd << ": pivot " << a[p] << " -> index " << p << " | " << show(a, a.size()) << "\n";
        if (p == k) break;
        if (k < p) hi = p - 1;
        else lo = p + 1;
    }
    return {a[k], comparisons};
}

int main() {
    vector<int> a = {3, 7, 6, 1, 8, 2, 9, 5, 4};
    auto [value, cost] = quickselect(a, 4, false, true);
    cout << "5th smallest: " << value << " (" << cost << " comparisons)\n";
    cout << "5 smallest: " << show(a, 5) << "\n";

    vector<int> s1 = {1, 2, 3, 4, 5, 6, 7, 8, 9}, s2 = s1;
    cout << "sorted, last pivot: " << quickselect(s1, 4).second << " comparisons\n";
    cout << "sorted, median of three: " << quickselect(s2, 4, true).second << " comparisons\n";

    vector<int> b = {3, 7, 6, 1, 8, 2, 9, 5, 4};
    cout << "2nd largest: " << quickselect(b, b.size() - 2).first << "\n";
    vector<int> one = {42};
    cout << "n = 1: " << quickselect(one, 0).first << "\n";
    vector<int> c = {3, 7, 6};
    try {
        quickselect(c, 5);
    } catch (const out_of_range&) {
        cout << "k = 5 on 3 values: rejected\n";
    }
}
import java.util.Arrays;

public class Main {
    static int comparisons;

    static String show(int[] a, int n) {
        return Arrays.toString(Arrays.copyOf(a, n));
    }

    static void swap(int[] a, int i, int j) {
        int t = a[i]; a[i] = a[j]; a[j] = t;
    }

    static int partition(int[] a, int lo, int hi) {
        int pivot = a[hi], store = lo;
        for (int j = lo; j < hi; j++)
            if (a[j] < pivot) swap(a, store++, j);
        swap(a, store, hi);
        comparisons += hi - lo;
        return store;
    }

    static int quickselect(int[] a, int k, boolean median3, boolean trace) {
        if (k < 0 || k >= a.length) throw new IndexOutOfBoundsException("k out of range");
        comparisons = 0;
        int lo = 0, hi = a.length - 1, rnd = 0;
        while (lo < hi) {
            if (median3) {
                int mid = (lo + hi) / 2;
                Integer[] idx = {lo, mid, hi};
                Arrays.sort(idx, (x, y) -> Integer.compare(a[x], a[y]));
                swap(a, idx[1], hi);
            }
            int p = partition(a, lo, hi);
            rnd++;
            if (trace) System.out.println("round " + rnd + ": pivot " + a[p] + " -> index " + p + " | " + show(a, a.length));
            if (p == k) break;
            if (k < p) hi = p - 1;
            else lo = p + 1;
        }
        return a[k];
    }

    public static void main(String[] args) {
        int[] a = {3, 7, 6, 1, 8, 2, 9, 5, 4};
        int value = quickselect(a, 4, false, true);
        System.out.println("5th smallest: " + value + " (" + comparisons + " comparisons)");
        System.out.println("5 smallest: " + show(a, 5));

        quickselect(new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9}, 4, false, false);
        System.out.println("sorted, last pivot: " + comparisons + " comparisons");
        quickselect(new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9}, 4, true, false);
        System.out.println("sorted, median of three: " + comparisons + " comparisons");

        int[] b = {3, 7, 6, 1, 8, 2, 9, 5, 4};
        System.out.println("2nd largest: " + quickselect(b, b.length - 2, false, false));
        System.out.println("n = 1: " + quickselect(new int[]{42}, 0, false, false));
        try {
            quickselect(new int[]{3, 7, 6}, 5, false, false);
        } catch (IndexOutOfBoundsException e) {
            System.out.println("k = 5 on 3 values: rejected");
        }
    }
}
Watch it run

Step through it

Running on [3, 7, 6, 1, 8, 2, 9, 5, 4], k = 4 (5th smallest)

find index k = 4 (5th smallest) · pivot = last value of the range307162138425965748live range 0..8 (all of it)k = 4comparisons so far: 0sorted, the array would read 1 2 3 4 5 6 7 8 9, so the answer is 5
Step 1

Goal: the 5th smallest of 9

Sorting would answer this, but it puts all nine values in order when only one position matters. Quickselect asks for the value that would sit at index 4 if the array were sorted, and does only enough work to place that one.

Output
1 / 13
4

Quickselect vs Quicksort and Heaps

Quickselect and quicksort both partition the same way. Quick sort then recurses into both sides because every position must end up correct. Quickselect recurses into one, because only position k matters. That single change drops the average cost from O(n log n) to O(n) and the worst case stays O(n²) for both.

Quickselect or a heap is the common choice for top-k problems. A heap of size k scans the input once in O(n log k), never reorders the input, and works on a stream that arrives one value at a time. Quickselect is O(n) on average but needs the whole array in memory and rearranges it. For one query over a fixed array, quickselect is usually faster; for streaming data or a guaranteed bound, use the heap. The heaps lesson covers the heap side.

Three ways to find the k-th smallest of n values
MethodTimeExtra spaceChanges the input?
Sort, then indexO(n log n)O(1) to O(n)Yes, or uses a copy
Heap of size kO(n log k)O(k)No; works on a stream
QuickselectO(n) average, O(n²) worstO(1)Yes, partially ordered
  • Need every value in order: sort
  • Values arrive one at a time, or k is small and the input must stay unchanged: heap
  • One query on an array you may rearrange: quickselect
5

Duplicates and Other Traps

Many equal values. A partition that sends only smaller values left puts the pivot at the left end of a run of equal values. With all values equal, each round removes one value and the cost becomes O(n²). A three-way partition groups less, equal and greater in one pass; if k falls inside the equal block, the search is over.

Forgetting the bounds. If k is outside 0..n − 1 there is no answer, and the range can shrink past k until the code reads outside the array. Check k before the first round.

Expecting a sorted result. After quickselect, the values left of k are all no larger than a[k] and those to the right are no smaller, but neither side is sorted. That is enough for top-k: slice indexes 0..k and sort that slice if the order matters, at O(k log k) extra.

  • Test an array of one value, k at both ends, and all values equal
  • Test sorted and reverse-sorted input with your pivot rule
  • Compare with a full sort on random arrays to check the index conversion
6

Practice and Next Steps

These problems are selection in disguise. Each can be solved by sorting; try quickselect and compare the running time.