Algorithm · Sorting and selection · O(n log n) expected, O(n²) worst
Quicksort
Partition around a pivot, then sort each side. O(n log n) expected, O(n²) worst case, in place, not stable.
The full derivation, edge cases and exercises are in the lesson Quicksort and partitioning. Open it full width in the playground.
On this page
The idea
Partitioning puts the pivot in its final position with smaller elements on its left and the rest on its right; the two sides are then sorted independently. The work is done before the recursion, the opposite of merge sort.
Balanced splits give O(n log n); a pivot that is always the minimum or maximum gives O(n²). The lab uses the middle element as pivot and the Lomuto scheme; production sorts use better pivots and switch to heap sort when recursion gets too deep (introsort).
Steps
- Choose a pivot (middle element) and move it to the end.
- Partition: everything smaller than the pivot to the left.
- Swap the pivot into the boundary; it is now final.
- Recurse on the left part and the right part.
Invariants
What holds at every step; the correctness argument rests on these.
- During partition: a[low … i) < pivot ≤ a[i … j); a[j … high) unseen.
- After partition the pivot never moves again.
Complexity
| Case | Time | Extra space | Notes |
|---|---|---|---|
| Expected / balanced splits | O(n log n) | O(log n) stack | |
| Worst case | O(n²) | O(n) stack | Consistently unbalanced pivots. |
When to use it
Use it when
- You need a fast in-place sort of primitive values and stability does not matter.
Avoid it when
- Inputs may be adversarial and you cannot afford the worst case.
- You need a stable sort.
Step through it
The interactive lab for quicksort: custom and seeded inputs, stepping forward and backward, with the active line highlighted in the code.
Implementation in four languages
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) < pivot <= 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) < pivot <= 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
Learn more
Lessons
- Quicksort and partitioning· M13 Sorting
Data structures it uses
Problems, patterns and exercises
- ProblemRed, white and blue in one pass· intermediate · O(n)
- Complexity exerciseTwo halves plus linear work· Θ(n log n)