Quicksort

Matt George

Fractional CTO · Founder of Injuria.ai

•20 min read•

Quicksort is an efficient, general-purpose sorting algorithm that employs a divide-and-conquer strategy to order elements within an array or list. Developed between 1959 and 1960 by British computer scientist Charles Antony Richard Hoare[1], it remains one of the most widely used algorithms in computer science. The algorithm operates by selecting a "pivot" element from the dataset and partitioning the remaining elements into two sub-arrays, based on whether they are less than or greater than the pivot. This process is then applied recursively to the sub-arrays until the entire dataset is sorted.

In its standard form, Quicksort is an in-place, unstable sorting algorithm. It requires minimal additional memory, operating with a space complexity of $O(\log n)$[2] due to the call stack generated by recursion. Its average-case time complexity is $O(n \log n)$[2], making it highly competitive with other $O(n \log n)$ algorithms like Merge Sort and Heapsort. However, Quicksort exhibits a worst-case time complexity of $O(n^2)$[2] if the pivot selection consistently results in highly unbalanced partitions.

Despite this theoretical worst-case behavior, Quicksort is frequently the algorithm of choice in practical software engineering.[28] Its inner loop is extremely short and relies on sequential memory access, which aligns perfectly with the caching architectures of modern central processing units. Over the decades, researchers and engineers have introduced numerous refinements to Hoare's original design, producing hybrid variants that guarantee optimal worst-case bounds while maintaining the algorithm's characteristic speed. The evolution of Quicksort mirrors the evolution of computer hardware itself, with modern implementations specifically tailored to exploit superscalar processor pipelines, minimize branch mispredictions, and maximize cache line utilization.

Definition and Problem Solved

The fundamental problem of sorting requires arranging a collection of items into a specified sequence, most commonly numerical or lexicographical order. Formally, given a sequence of $n$ elements, a sorting algorithm must output a permutation of those elements such that each element is less than or equal to the subsequent element, according to a defined total order relation. A total order relation ensures that for any two elements, either one is strictly less than the other, or they are equivalent in rank.

Quicksort addresses this problem by breaking the larger sorting task into smaller, independent sub-tasks using the divide-and-conquer paradigm. Unlike algorithms that build a sorted sequence iteratively (such as Insertion Sort) or algorithms that sort by merging pre-sorted halves (such as Merge Sort), Quicksort does its primary work during the division phase. The core invariant of Quicksort is that after a partitioning step, this is true for the Lomuto partition scheme, but in the Hoare partition scheme, the pivot is not necessarily placed in its final position. All elements to the left of the pivot are guaranteed to be smaller than or equal to the pivot, and all elements to the right are guaranteed to be greater than or equal to it.

Because the two resulting sub-arrays are completely independent, no merging or combining phase is required after the recursive calls return. The array is sorted entirely in place. This property solves a significant resource allocation problem. While Merge Sort requires $O(n)$ auxiliary memory to hold the merged elements, Quicksort rearranges the elements within the existing memory boundaries, requiring only a small amount of stack space for the recursive function calls. This makes Quicksort highly suitable for systems with constrained memory resources or for processing large datasets that fit entirely in random-access memory.

In modern computing, the in-place nature of Quicksort provides a performance advantage due to the cache hierarchy[3]. Central processing units operate orders of magnitude faster than main memory. To bridge this gap, processors use small, ultra-fast hardware caches. When an algorithm requests data from memory, the processor fetches an entire cache line (typically 64 bytes) into the cache. Because Quicksort partitions arrays by scanning contiguous memory addresses sequentially, it exhibits excellent spatial locality. The processor successfully prefetches the required data, minimizing CPU stalls. In contrast, algorithms that allocate separate memory buffers or rely on scattered pointer traversals frequently suffer from cache misses, forcing the processor to wait hundreds of clock cycles for data to arrive from main RAM.

A fundamental tradeoff of Quicksort's in-place partitioning is its lack of stability. A stable sorting algorithm preserves the relative order of elements that possess equal sort keys. If a dataset of employees is initially sorted by alphabetical name, and then subsequently sorted by department, a stable sort guarantees that employees within the same department will remain in alphabetical order. Quicksort achieves its efficiency by swapping elements across large distances during the partitioning phase, which inherently scrambles the original relative ordering of equal keys. While stability can be artificially induced by appending the original index to each key, this increases memory overhead and negates many of Quicksort's performance benefits.

Mechanism and Complexity

The Quicksort algorithm consists of three primary steps: pivot selection, partitioning, and recursion.

The first step involves choosing a pivot element from the array. The choice of pivot heavily influences the algorithm's performance, as it dictates the balance of the resulting partitions. A naive implementation might simply select the first or last element of the array. While easy to implement, this strategy performs poorly on arrays that are already sorted or nearly sorted, leading to highly unbalanced partitions where one sub-array contains $n-1$ elements and the other contains zero.

To address this, more sophisticated implementations employ randomized or sampled pivot selection. Choosing a random element guarantees that no specific input pattern can consistently force the worst-case behavior, though generating random numbers incurs computational overhead. A widely adopted deterministic approach is the median-of-three method, which samples the first, middle, and last elements of the partition and selects their median value as the pivot. For even stronger guarantees, algorithms can use the median-of-medians algorithm, introduced by [4]. This algorithm finds an approximate median in guaranteed linear time, ensuring that the partitions are never worse than a 30 to 70 split. While capable of guaranteeing an $O(n \log n)$ worst-case time complexity for Quicksort, the median-of-medians approach carries a high constant factor overhead and is rarely used in practical sorting libraries.

Once the pivot is chosen, the partitioning phase begins. The goal is to rearrange the array such that all elements less than the pivot precede it, and all elements greater than the pivot follow it. There are two standard partitioning schemes used in Quicksort implementations: the Lomuto partition scheme and the Hoare partition scheme.

The Lomuto partition scheme[2], often taught in introductory computer science courses due to its simplicity, maintains an index that tracks the boundary between the smaller and larger elements. As it iterates through the array, any element smaller than the pivot is swapped into the smaller section, and the boundary index is incremented. Finally, the pivot is swapped into its correct position at the boundary. While conceptually straightforward, the Lomuto scheme is suboptimal in practice. It performs a high number of swaps, particularly when the array contains many duplicate elements, degrading performance to $O(n^2)$ if all elements are equal.

The Hoare partition scheme[5], described in the original 1962 paper[5], uses two pointers that start at opposite ends of the array and move toward each other. The left pointer advances until it finds an element greater than or equal to the pivot, and the right pointer moves backward until it finds an element less than or equal to the pivot. If the pointers have not crossed, the two elements are swapped. This process continues until the pointers cross, at which point the array is partitioned. The Hoare scheme is generally more efficient than the Lomuto scheme because it performs approximately three times fewer swaps on average. It naturally halts on equal elements, distributing them evenly across the two partitions and preventing quadratic degradation on arrays with identical keys.

function quicksort(A, lo, hi)
    if lo >= 0 and hi >= 0 and lo < hi then
        p := partition(A, lo, hi)
        quicksort(A, lo, p)
        quicksort(A, p + 1, hi)

function partition(A, lo, hi)
    pivot := A[floor((hi + lo) / 2)]
    i := lo - 1
    j := hi + 1
    loop forever
        do i := i + 1 while A[i] < pivot
        do j := j - 1 while A[j] > pivot
        if i >= j then
            return j
        swap A[i] with A[j]

After partitioning, the algorithm recursively calls itself on the sub-array to the left of the pivot and the sub-array to the right. The base case for the recursion is an array of zero or one element, which is inherently sorted.

The performance of Quicksort is mathematically modeled using a recurrence relation. Let $T(n)$ represent the time taken to sort an array of $n$ elements. The partitioning step takes $\Theta(n)$ time. If the pivot divides the array into two sub-arrays of sizes $k$ and $n - k - 1$, the recurrence is $T(n) = T(k) + T(n - k - 1) + \Theta(n)$.

In the best-case scenario, the pivot divides the array into two equal halves at every step. The depth of the recursion tree is $\log_2 n$, and at each level, the algorithm performs $O(n)$ comparisons. By the Master Theorem[2], this resolves to a best-case time complexity of $O(n \log n)$. The average-case time complexity, assuming all permutations of the input are equally likely, is also mathematically proven to be $O(n \log n)$. This is calculated by summing the costs over all possible pivot choices and dividing by $n$. Using indicator random variables to count the expected number of comparisons between any two elements, the rigorous mathematical proof demonstrates that the average number of comparisons is approximately $2n \ln n$, which translates to roughly $1.386n \log_2 n$. This low constant factor is a primary reason for Quicksort's practical dominance.

In the worst-case scenario, the pivot consistently partitions the array into one sub-array of size $n-1$ and another of size 0. This occurs, for example, when using a naive pivot selection on an already sorted array. The recursion tree becomes a linear chain of depth $n$, resulting in $n$ levels of $O(n)$ comparisons, yielding a worst-case time complexity of $O(n^2)$.

The space complexity of Quicksort is dictated by the call stack. In the worst case, a naive implementation requires $O(n)$ stack space, which can lead to stack overflow errors on large datasets. Hoare recognized this limitation and proposed a refinement in 1962: the algorithm should always execute the recursive call on the smaller sub-array first, and use a tail call (or an explicit loop) to sort the larger sub-array. This optimization guarantees that the maximum depth of the call stack never exceeds $O(\log n)$, strictly bounding the auxiliary space requirement.

Discovery and History

Quicksort was invented by Tony Hoare between 1959 and 1960.[29] At the time, Hoare was a visiting student at Moscow State University in the Soviet Union, studying probability theory under the eminent mathematician Andrey Kolmogorov[6]. Concurrently, he was working on a machine translation project for the National Physical Laboratory[7] in the United Kingdom, which aimed to translate Russian text into English.

The translation process required looking up Russian words in a bilingual dictionary stored on a single reel of magnetic tape. Because magnetic tape is a sequential access medium, it was computationally infeasible to search the tape for each word in the order it appeared in the text. If the translation program encountered the words in the order they appeared in the Russian sentence, the tape drive would have to wind forward and backward continuously, which was mechanically slow and prone to failure. By sorting the words of the sentence into alphabetical order first, the computer could read the tape strictly forward, extracting all necessary translations in a single pass.

Hoare initially considered using Insertion Sort for this task but quickly realized its $O(n^2)$ performance would be too slow for the volume of data. He then conceived the idea of partitioning the data around a chosen element. He wrote the first implementation of the partitioning logic in Mercury Autocode[8], a programming language used on the Ferranti Mercury computer[9]. However, he struggled to manage the list of unsorted segments without the use of recursion, which Mercury Autocode did not support. He had to manually simulate the call stack using an array to keep track of the boundaries of the unsorted segments, a process that proved highly error-prone and difficult to optimize.

Upon returning to England in 1960, Hoare took a position as a programmer at Elliott Brothers, a British computer manufacturing company. His supervisor asked him to implement Shellsort, which was considered the fastest sorting algorithm at the time. Hoare informed his boss that he had invented a faster algorithm, leading to a bet of sixpence[7]. Hoare subsequently learned ALGOL 60[1], a newly developed programming language that natively supported recursive procedures. Because his work at Elliott Brothers involved writing a compiler for ALGOL 60, he was intimately familiar with the language's specification. The availability of recursion allowed Hoare to express the Quicksort algorithm elegantly and correctly, winning the bet.

Hoare published the algorithm in 1961[10] in the Communications of the ACM as Algorithm 63 (Partition) and Algorithm 64 (Quicksort)[10]. The following year, he published a comprehensive theoretical analysis of the algorithm in The Computer Journal, detailing its expected performance, the Hoare partition scheme, and the $O(\log n)$ space optimization.

The mathematical foundation of Quicksort was later solidified by Robert Sedgewick[11]. In 1975, Sedgewick completed his PhD thesis, "Quicksort", at Stanford University under the supervision of Donald Knuth[11]. Sedgewick's thesis provided an exhaustive mathematical analysis of the algorithm, resolving several open questions regarding its average-case behavior, the exact number of comparisons and swaps, and the optimal strategies for pivot selection and handling small sub-arrays. In 1978, Sedgewick published "Implementing Quicksort Programs"[12] in the Communications of the ACM, translating his theoretical findings into practical engineering guidelines. Sedgewick demonstrated that for very small arrays, the overhead of Quicksort's recursion outweighs its benefits, and he recommended falling back to Insertion Sort for sub-arrays smaller than a specific threshold (typically between 10 and 20 elements). This optimization remains a standard feature in almost all modern Quicksort implementations.

Important Variants

Since its publication, Quicksort has undergone extensive engineering to address its worst-case vulnerabilities and adapt it to modern hardware architectures.

Bentley-McIlroy Quicksort (1993)
In 1993, Jon Bentley and M. Douglas McIlroy[13] published "Engineering a Sort Function"[13] in Software: Practice and Experience.[29] They designed a highly optimized version of Quicksort for the C standard library. Their implementation introduced a resilient pivot selection method called the ninther (the median of three medians of three) to prevent worst-case behavior on common input patterns. They addressed the Dutch National Flag problem[14] (formulated by Edsger W. Dijkstra) by implementing a three-way partitioning scheme. Dijkstra's problem asks how to sort an array of balls colored red, white, and blue, such that all balls of the same color are contiguous. Bentley and McIlroy adapted this to Quicksort by treating elements less than the pivot as red, equal to the pivot as white, and greater than the pivot as blue. Their implementation maintains four pointers to group equal elements at the ends of the array during the partitioning scan, and then swaps them into the middle next to the pivot. This ensures that sub-arrays of identical elements are not recursively sorted, drastically improving performance on arrays with many duplicate keys and reducing the time complexity from $O(n \log n)$ to $O(n)$ in cases where the number of distinct keys is small.

Introsort (1997)
Invented by David R. Musser in 1997[15], Introspective Sort (Introsort)[15] is a hybrid algorithm that eliminates Quicksort's $O(n^2)$ worst-case time complexity while preserving its average-case speed. Introsort begins by executing standard Quicksort. However, it tracks the recursion depth. If the depth exceeds a predetermined threshold (usually $2 \lfloor \log_2 n \rfloor$), the algorithm detects that it is degenerating toward the worst case and immediately switches to Heapsort for the remaining sub-array. Heapsort guarantees $O(n \log n)$ worst-case performance but is generally slower than Quicksort on average due to poorer cache locality. By combining the two, Introsort achieves the best of both worlds. Introsort is the standard sorting algorithm in many modern implementations of the C++ Standard Template Library.

Dual-Pivot Quicksort (2009)
In 2009, Vladimir Yaroslavskiy[16] proposed a Dual-Pivot Quicksort algorithm[16]. Instead of a single pivot, Yaroslavskiy's method selects two pivots, $P_1$ and $P_2$ (where $P_1 \le P_2$), and partitions the array into three segments: elements less than $P_1$, elements between $P_1$ and $P_2$, and elements greater than $P_2$. The algorithm maintains three pointers: $L$ (less), $K$ (current), and $G$ (greater). As $K$ scans the array, elements are placed into the left segment if they are less than $P_1$, the right segment if they are greater than $P_2$, or left in the middle segment. Historically, multi-pivot Quicksort variants were considered theoretically inferior because they perform more comparisons. However, Yaroslavskiy demonstrated that his specific implementation performed fewer memory operations and exhibited better cache locality on modern processors. Mathematical analysis by Sebastian Wild and Markus E. Nebel[17] later confirmed that Dual-Pivot Quicksort reduces the number of cache misses. Because the algorithm divides the array into three smaller segments rather than two, the subsequent recursive calls operate on smaller memory ranges sooner, fitting into the L1 and L2 CPU caches more effectively.

BlockQuicksort (2016)
Modern processors rely heavily on branch prediction[18] to maintain the flow of instructions through their superscalar pipelines. The conditional branches in standard Quicksort partitioning (checking if an element is less than the pivot) are highly unpredictable, leading to frequent pipeline flushes that stall the CPU. In 2016, Stefan Edelkamp and Armin Weiss introduced BlockQuicksort[19], a variant designed to bypass this hardware bottleneck. BlockQuicksort processes elements in small blocks, filling temporary buffers with the indices of elements that need to be swapped. By using bitwise operations and conditional moves instead of branching logic, the algorithm eliminates branch mispredictions during the inner partitioning loop. This hardware-sympathetic approach yields significant performance gains on modern architectures, often outperforming traditional Quicksort implementations by a wide margin.

Pattern-Defeating Quicksort (2016)
Pattern-defeating quicksort (pdqsort)[20], developed by Orson Peters in 2014 to 2015[20], is a modern hybrid algorithm designed to achieve $O(n)$ time complexity on arrays that are already sorted or strictly reverse-sorted. It combines the fast average case of Quicksort with the worst-case guarantees of Heapsort (similar to Introsort), but adds heuristics to detect patterns in the input data. If pdqsort detects that a sub-array is already sorted, it bypasses partitioning entirely. If it detects a strictly descending pattern, it reverses the sub-array in linear time. It incorporates the branchless partitioning techniques of BlockQuicksort, making it one of the fastest general-purpose sorting algorithms available today.

Real-World Applications

Quicksort and its variants form the backbone of sorting infrastructure across numerous programming languages and operating systems.[28]

In the C programming language, the standard library function qsort[21] is named after Quicksort. While the C specification does not mandate a specific algorithm, historical implementations relied heavily on the Bentley-McIlroy variant. However, modern implementations vary. The GNU C Library (glibc), used in most Linux distributions, is a prime example of pragmatic engineering overriding nomenclature. Despite the name, the glibc implementation of qsort[22] attempts to allocate temporary memory using malloc to perform a Merge Sort, because Merge Sort provides stable sorting and a guaranteed $O(n \log n)$ worst-case time. However, if the system is under memory pressure and malloc fails, the function automatically falls back to Heapsort. This hybrid approach ensures that the function never fails due to memory exhaustion while providing high performance in the common case.

In the Java ecosystem, Quicksort is deeply integrated. When a developer calls java.util.Arrays.sort()[23] on an array of primitive data types (such as integers or floating-point numbers), the Java Virtual Machine executes Vladimir Yaroslavskiy's Dual-Pivot Quicksort. This change was integrated into Java 7 after extensive benchmarking proved it outperformed the previous standard Quicksort implementation.

The C++ Standard Library function std::sort[24] requires an algorithm with an $O(n \log n)$ worst-case complexity. Consequently, nearly all major C++ standard library implementations (including GCC's libstdc++ and LLVM's libc++) use Musser's Introsort, which relies on Quicksort for the vast majority of its operations.

The Rust programming language standard library uses Orson Peters' pdqsort for its slice::sort_unstable function, capitalizing on its pattern-defeating heuristics and branchless partitioning to achieve high performance on partially sorted data.

Conversely, the V8 JavaScript engine[25] (which powers Google Chrome and Node.js) provides a notable example of a system moving away from Quicksort. For years, V8 implemented Array.prototype.sort()[26] using an unstable Quicksort for arrays longer than 10 elements. However, web developers frequently relied on the sort being stable (preserving the original order of equal elements). If a developer sorted an array of users by age, and then sorted the same array by last name, they expected the users with the same last name to remain sorted by age. The unstable Quicksort destroyed the initial ordering. To resolve this, the ECMAScript committee updated the language specification to mandate stable sorting. Consequently, V8 engineers replaced the Quicksort implementation with Timsort[25] in 2018.

Significance and Tradeoffs

The enduring performance of Quicksort is largely attributed to its hardware sympathy. While algorithms like Merge Sort and Heapsort share its $O(n \log n)$ average time complexity, Quicksort typically outperforms them in practice due to its memory access patterns. The partitioning phase of Quicksort reads and writes memory in a strictly linear, sequential fashion. This behavior perfectly matches the design of CPU caches, which prefetch adjacent memory addresses. Consequently, Quicksort minimizes cache misses and maximizes memory bandwidth utilization.

Additionally, the in-place nature of Quicksort makes it highly versatile. It does not require the memory allocator to find large contiguous blocks of free RAM, which is a strict requirement for the standard implementation of Merge Sort. This makes Quicksort indispensable in embedded systems and operating system kernels where memory allocation is tightly constrained or unpredictable.

Quicksort is not universally applicable. Its primary tradeoff is its lack of stability. In applications where the relative order of equal elements must be preserved, Quicksort will disrupt the initial ordering. In these scenarios, stable algorithms like Merge Sort or Timsort are required.

Standard Quicksort is not suitable for external sorting. When a dataset is too large to fit into main memory and must reside on disk, the random-access nature of Quicksort's pivot selection and pointer crossing becomes prohibitively slow due to disk seek times. In such cases, external Merge Sort is the standard solution.

Finally, in environments where algorithmic complexity attacks are a security concern, the theoretical $O(n^2)$ worst-case of a deterministic Quicksort is a critical vulnerability. If an attacker can control the input data fed to a server, they can craft a malicious payload designed to trigger the worst-case partitioning behavior, causing a denial-of-service attack by monopolizing CPU resources. This vulnerability was famously detailed by M. Douglas McIlroy in his 1999 paper "A Killer Adversary for Quicksort"[27], which demonstrated how an adversary could dynamically generate worst-case inputs for any deterministic Quicksort implementation. To address this risk, secure systems must employ randomized pivot selection, cryptographic hashing of inputs, or hybrid algorithms like Introsort that guarantee an absolute $O(n \log n)$ upper bound regardless of the input distribution.

Sources (29)
  1. Charles Antony Richard Hoare
  2. mitpress.mit.edu: space complexity of $O(\log n)$
  3. Wikipedia: cache hierarchy
  4. doi.org
  5. Hoare partition scheme
  6. mathshistory.st-andrews.ac.uk: Andrey Kolmogorov
  7. machine translation project for the National Physical Laboratory
  8. Wikipedia: Mercury Autocode
  9. Ferranti Mercury computer
  10. ACM Digital Library
  11. Robert Sedgewick
  12. "Implementing Quicksort Programs"
  13. Jon Bentley and M. Douglas McIlroy
  14. ACM Digital Library
  15. David R. Musser in 1997
  16. Vladimir Yaroslavskiy
  17. Sebastian Wild and Markus E. Nebel
  18. Wikipedia: branch prediction
  19. BlockQuicksort
  20. Pattern-defeating quicksort (pdqsort)
  21. standard library function `qsort`
  22. GNU Project
  23. `java.util.Arrays.sort()`
  24. `std::sort`
  25. V8 JavaScript engine
  26. `Array.prototype.sort()`
  27. cs.dartmouth.edu: "A Killer Adversary for Quicksort"
  28. Steven S Skiena, The Algorithm Design Manual (Springer Science & Business Media, 2009)
  29. Greg Wilson, Andy Oram, Beautiful Code ("O'Reilly Media, Inc.", 2007)

Recommended reading