Essential cookies keep your basket and sign-in working. Optional cookies help us understand visits and measure ads. Privacy details.
Efficient divide-and-conquer sorting algorithm with average O(n log n) complexity.
function quicksort(arr, low, high):
if low < high:
pivot = partition(arr, low, high)
quicksort(arr, low, pivot - 1)
quicksort(arr, pivot + 1, high)
function partition(arr, low, high):
pivot = arr[high]
i = low - 1
for j = low to high - 1:
if arr[j] <= pivot:
i++
swap(arr[i], arr[j])
swap(arr[i + 1], arr[high])
return i + 1AI-assisted explanation. It may contain errors; use a textbook or original source to check important details.
Quicksort isn’t a single equation so much as a beautiful idea: to sort a messy list, pick one “reference” element (the pivot), split everything into two groups—things smaller than the pivot and things larger—and then sort each group the same way. It’s like organizing books by choosing one book as a divider: put all titles that come before it on the left shelf, all that come after on the right shelf, and then repeat the process on each shelf until every shelf segment is trivially ordered. The reason people summarize Quicksort with “average O(n log n)” is that, in typical situations, each partition step scans the list once (about n work) and the pivot tends to split the list into reasonably balanced halves. Balanced splitting creates about log2(n) levels of recursion, so you get roughly “n work per level × log n levels” → n log n. The main “characters” in the story are: - n: the number of items to sort. - pivot: the chosen element used to divide the list. - partition: the operation that rearranges items so smaller-than-pivot go left, larger-than-pivot go right. - recursion: applying the same strategy to the left and right parts. One subtlety makes Quicksort especially interesting: its speed depends on pivot choice. If the pivot repeatedly splits very unevenly (e.g., always the smallest element), Quicksort can degrade to O(). But with good pivot selection (random pivot, median-of-three, etc.), it’s typically fast in practice and cache-friendly.
Quicksort was developed in the late 1950s when computers were far more limited in memory and speed, and sorting was (and still is) a foundational task. Tony Hoare conceived Quicksort around 1959 while working on a project involving machine translation in Moscow, where efficient data handling mattered. The breakthrough was the partitioning insight: you can reorganize data around a pivot in a single pass and then recursively sort smaller subproblems. Hoare published the algorithm in 1961, and it quickly became a landmark example of divide-and-conquer thinking—showing how a simple local operation (partition) can produce global order through recursion.
Pioneered by: C. A. R. (Tony) Hoare