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

Quicksort

Lomuto partition around the middle element, with the recursion stack shown.

The full explanation, derivation and practice are in the lesson Quicksort and partitioning.

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.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