QuickSort / QuickSelect

Partition an array around a pivot so the pivot lands in its final place. Sort both sides for quicksort, or follow only the side that holds index k for quickselect, which finds the k-th value in O(n) expected time.

Overview

The idea

Quicksort picks one value, the pivot, and partitions the array: everything smaller goes to the pivot's left and everything larger to its right. After that one pass the pivot is in its final sorted position and never moves again. Then the same is done to the left part and the right part. Tony Hoare developed it in 1959 and published it in 1961.

Watch it sort 3 2 1 5 6 4, always taking the last value as the pivot. The first pivot is 4. The partition puts 3 2 1 on its left and 6 5 on its right, and 4 is now in its final place. The left part, 3 2 1, takes 1 as its pivot. Nothing is smaller than 1, so 1 is placed and 2 3 remains, which takes 3 as its pivot and places 2 and 3. The right part, 6 5, takes 5 as its pivot, which places 5 and leaves 6. Each pivot lands in its final place, and the two sides are sorted by the same steps.

Quickselect is the same partition with one change: instead of sorting both sides, follow only the side that contains the index you want. That finds the k-th smallest value without sorting the rest.

That one change shifts every cost. After a partition, quicksort recurses on both sides, while quickselect continues on one side. So quicksort's expected time is O(n log n), and quickselect's is O(n). Both have an O(n²) worst case. Quicksort needs an O(log n) stack if it recurses on the smaller side first, while quickselect needs only O(1) when written as a loop. Neither keeps the input as it was: quicksort is not stable, and quickselect changes the array.

Everything in both algorithms rests on the partition, so the chapter starts there.

Sign up free to read the full topic

More Coding & DSA topics

Start free on Cariara · Coding problems · System design studio