Sorting · O(n) expected, O(n²) worst

Quickselect

Partition around the middle element and keep only the side that holds index k.

The full explanation, derivation and practice are in the lesson Divide and conquer: recurrences, the Master theorem and quickselect.

Implementation

The code the visualizer highlights, in four languages. Each is tested against one shared set of cases and a randomized comparison with the language's built-in equivalent.

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