Overview

Quicksort is a comparison-based, divide-and-conquer sorting algorithm designed to reorder the elements of an array or list. It repeatedly partitions a sequence around a chosen pivot so that values less than the pivot come before it and values greater come after, then recursively sorts the parts. This approach makes Quicksort both conceptually simple and, in typical cases, very fast for large datasets. For a general introduction see Quicksort.

How it works

The central steps are selection of a pivot and partitioning the current segment into two subsegments. A common, minimal outline is:

  1. Choose a pivot element from the segment.
  2. Rearrange elements so that those less than the pivot are left and those greater are right (the pivot is placed in its final position).
  3. Recursively apply the same process to the left and right subsegments until segments are trivially small.

Partitioning can be implemented in-place, so Quicksort often requires little extra memory besides recursion stack space.

Performance and complexity

On average Quicksort runs in O(n log n) time, which is why it is widely favored. However, a poor pivot choice can degrade performance to O(n^2) in the worst case. Typical implementations reduce this risk by randomizing the pivot or using pivot-selection heuristics. Space usage is usually O(log n) for the recursion stack in balanced cases.

Variants and practical details

Implementations differ mainly in their partition scheme and safeguards. Notable choices include:

  • Hoare partition — often faster and uses fewer swaps.
  • Lomuto partition — simpler to code but can be less efficient.
  • Three-way partitioning — groups elements less than, equal to, and greater than the pivot; useful with many duplicates.
  • Randomized pivot and median-of-three heuristics
  • Hybrid approaches such as switching to insertion sort for small subarrays or using introsort (fall back to heapsort) to avoid worst-case behavior.

History and adoption

Quicksort was developed by Tony Hoare in the late 1950s and has been refined since. Its combination of low overhead, good locality of reference, and excellent average performance made it a default choice in many library implementations and systems software.

Notable properties and cautions

Quicksort is usually not stable (equal elements may be reordered) unless modified. It is favored when in-place sorting and average speed matter, but for guaranteed worst-case performance one might choose mergesort or heapsort. Careful pivot selection, tail-recursion elimination, and hybridization are common practical measures to make Quicksort robust in real applications.