Algorithm · Sorting and selection · O(n) expected, O(n²) worst

Quickselect

Partition like quicksort but keep only the side that holds index k: the k-th smallest element in O(n) expected time, in place.

The full derivation, edge cases and exercises are in the lesson Divide and conquer: recurrences, the Master theorem and quickselect. Open it full width in the playground.

On this page
  1. The idea
  2. Steps
  3. Invariants
  4. Complexity
  5. When to use it
  6. Step through it
  7. Implementation
  8. Learn more
  9. References

The idea

After one partition the pivot is at its sorted position p. If p = k you are done; otherwise the answer is on one side only, so the other side is never touched. The ranges shrink geometrically on average, giving n + n/2 + n/4 + … = O(n).

With a deterministic middle pivot, adversarial input can still force O(n²); median-of-medians gives a guaranteed O(n) at a higher constant.

Steps

  1. Partition [low, high] around the middle element.
  2. If the pivot lands at k, return it.
  3. Otherwise continue with the part that contains k.

Invariants

What holds at every step; the correctness argument rests on these.

  • Everything left of the range is ≤ the answer, everything right of it is ≥ the answer.
  • Index k always lies inside the current range.

Complexity

Quickselect complexity
CaseTimeExtra space
ExpectedO(n)O(1) iterative
Worst caseO(n²)O(1)

When to use it

Use it when

  • You need the median, a percentile or the k-th element once, and may reorder the array.

Avoid it when

  • You need many order statistics from the same data (sort once).
  • The array must not be modified (copy it, or use a heap of size k).

Step through it

The interactive lab for quickselect: custom and seeded inputs, stepping forward and backward, with the active line highlighted in the code.

Implementation in four languages

Quickselect in four languages, each checked against one shared fixture (the k-th value, the exact comparison count and the array order left behind, including all-equal input, duplicates, negatives and k at both ends) and 500 random arrays compared with sorting, with the result partitioned around k.

namespace Bekadan.Dsa.Examples.DivideAndConquer;
 
/// <summary>
/// Quickselect: the k-th smallest item (k is 0-based: 0 is the minimum,
/// n - 1 the maximum). Lomuto partition with the middle element as pivot, then
/// keep only the side that contains index k. In place: the array is reordered
/// so that items[k] holds the answer, smaller-or-equal items are left of it and
/// greater-or-equal items right of it.
/// O(n) comparisons on average, O(n²) in the worst case (for example, all keys
/// equal and k = n - 1). Iterative, so the stack depth is O(1).
/// </summary>
public static class Quickselect
{
    public static T Select<T>(T[] items, int k, Comparison<T> compare)
    {
        if (k < 0 || k >= items.Length)
            throw new ArgumentOutOfRangeException(nameof(k), $"k must be from 0 to {items.Length - 1}.");
        int low = 0, high = items.Length - 1;
        while (true)
        {
            if (low == high)
                return items[low]; // one slot left: it must be index k
            int p = Partition(items, low, high, compare);
            if (k == p)
                return items[p]; // the pivot landed exactly on k
            if (k < p)
                high = p - 1; // discard the pivot and everything right of it
            else
                low = p + 1; // discard the pivot and everything left of it
        }
    }
 
    /// <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/DivideAndConquer/Quickselect.cs

"""Quickselect: the k-th smallest item (k is 0-based: 0 is the minimum, n - 1 the maximum).
 
Lomuto partition with the middle element as pivot, then keep only the side that
contains index k. In place: afterwards items[k] holds the answer, with
smaller-or-equal items to its left and greater-or-equal items to its right.
O(n) comparisons on average, O(n^2) in the worst case (for example, all keys
equal and k = n - 1). Iterative, so there is no recursion depth to worry about.
"""
 
from collections.abc import Callable
from typing import Any
 
 
def _identity(item: Any) -> Any:
    return item
 
 
def quickselect(items: list[Any], k: int, key: Callable[[Any], Any] = _identity) -> Any:
    if not 0 <= k < len(items):
        raise IndexError(f"k must be from 0 to {len(items) - 1}")
    low, high = 0, len(items) - 1
    while True:
        if low == high:
            return items[low]  # one slot left: it must be index k
        p = _partition(items, low, high, key)
        if k == p:
            return items[p]  # the pivot landed exactly on k
        if k < p:
            high = p - 1  # discard the pivot and everything right of it
        else:
            low = p + 1  # discard the pivot and everything left of it
 
 
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/quickselect.py

package dev.bekadan.dsa.divideconquer;
 
import java.util.Comparator;
 
/**
 * Quickselect: the k-th smallest item (k is 0-based: 0 is the minimum, n - 1 the maximum).
 * Lomuto partition with the middle element as pivot, then keep only the side that contains
 * index k. In place: afterwards items[k] holds the answer, with smaller-or-equal items to its
 * left and greater-or-equal items to its right. O(n) comparisons on average, O(n²) in the
 * worst case (for example, all keys equal and k = n - 1). Iterative, so the stack depth is O(1).
 */
public final class Quickselect {
    private Quickselect() {
    }
 
    public static <T> T select(T[] items, int k, Comparator<? super T> comparator) {
        if (k < 0 || k >= items.length) {
            throw new IndexOutOfBoundsException("k must be from 0 to " + (items.length - 1));
        }
        int low = 0;
        int high = items.length - 1;
        while (true) {
            if (low == high) {
                return items[low]; // one slot left: it must be index k
            }
            int p = partition(items, low, high, comparator);
            if (k == p) {
                return items[p]; // the pivot landed exactly on k
            }
            if (k < p) {
                high = p - 1; // discard the pivot and everything right of it
            } else {
                low = p + 1; // discard the pivot and everything left of it
            }
        }
    }
 
    /** 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/divideconquer/Quickselect.java

#pragma once
 
#include <cstddef>
#include <functional>
#include <span>
#include <stdexcept>
#include <utility>
 
namespace bekadan::dsa {
 
// Quickselect: the k-th smallest item (k is 0-based: 0 is the minimum, n - 1 the maximum).
// Lomuto partition with the middle element as pivot, then keep only the side that contains
// index k. In place: afterwards items[k] holds the answer, with smaller-or-equal items to its
// left and greater-or-equal items to its right. O(n) comparisons on average, O(n²) in the
// worst case (for example, all keys equal and k = n - 1). Iterative: O(1) stack depth.
// The standard library's std::nth_element does the same job (with a guaranteed bound).
 
namespace detail {
 
// Returns the pivot's final index p: items[low..p) < pivot <= items(p..high].
template <typename T, typename Less>
std::size_t select_partition(std::span<T> items, std::size_t low, std::size_t high, Less& less) {
    const std::size_t mid = low + (high - low) / 2;
    std::swap(items[mid], items[high]);  // park the middle element at the end
    const T pivot = items[high];
    std::size_t i = low;  // items[low..i) < pivot
    for (std::size_t j = low; j < high; ++j) {
        if (less(items[j], pivot)) {
            std::swap(items[i], items[j]);
            ++i;
        }
    }
    std::swap(items[i], items[high]);  // the pivot lands in its final place
    return i;
}
 
}  // namespace detail
 
template <typename T, typename Less = std::less<T>>
T quickselect(std::span<T> items, std::size_t k, Less less = Less{}) {
    if (k >= items.size()) throw std::out_of_range("k must be smaller than the number of items");
    std::size_t low = 0;
    std::size_t high = items.size() - 1;
    while (true) {
        if (low == high) return items[low];  // one slot left: it must be index k
        const std::size_t p = detail::select_partition(items, low, high, less);
        if (k == p) return items[p];  // the pivot landed exactly on k
        if (k < p) high = p - 1;  // discard the pivot and everything right of it (p > k >= low, so no underflow)
        else low = p + 1;  // discard the pivot and everything left of it
    }
}
 
}  // namespace bekadan::dsa

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

Learn more

Data structures it uses

Problems, patterns and exercises

References