Quick sort

A pivot and 2 sides · Part of Search and sort

Key idea

Practice

6 questions · about 3 min

Explained step by step

Quick sort

Quick sort's core operation is partitioning. An element is chosen as the pivot, for example the first, and the array is rearranged so all smaller values end up on its left and all larger ones on its right. It's done with 2 pointers starting at the 2 ends: one looks from the left for an element larger than the pivot, the other from the right for a smaller one, and they're swapped. When they meet, the pivot goes to its final place.

Quick sort uses divide and conquer. First it partitions the array with a pivot, leaving an unsorted left side and an unsorted right side. Then it does the same with each side, recursively: picks a pivot in each and partitions it. It stops when a piece has 1 element, which is already sorted. Since each pivot lands in its place, at the end everything is sorted, with no merge step.

On average, quick sort has about log n levels of partitioning, and at each level it walks n elements in total: O(n log n). In the worst case, if each pivot lands at an end, there are n levels and it costs O(n²). It sorts in place, with no extra array, but the recursion uses the stack: O(log n) on average and up to O(n) in the worst case. It isn't stable: the pivot's final swap can jump over an equal value. And it isn't adaptive.

Quick sort has the same average complexity as merge sort and heap sort, O(n log n), but in practice it's usually the fastest, for 3 reasons. The worst case, O(n²), almost never happens. It uses the cache very well, because it walks contiguous pieces of the array. And it does fewer comparisons, assignments and swaps in total than the other 2: its constant is smaller.

With certain data, quick sort gets slow. If the array comes reverse-sorted and the first element is always chosen as the pivot, each partition leaves one side empty and the other with n − 1: there are n levels and it costs O(n²). To avoid it, the pivot is chosen better: at random, or better, the median of 3 candidates, the first, the middle and the last. That makes it very rare for the pivot to be the smallest or the largest.

In the worst case, quick sort's recursion can reach n levels and use O(n) stack memory. To avoid it, after each partition the 2 sides' lengths are compared and the recursive call is made only on the shorter one; the longer one keeps being processed with a loop. Since the shorter side has at most n / 2 elements, the depth stays at O(log n).

Terms in this lesson

Arki, the beaver mascot

Your next interview starts with 5 minutes today.

Free on iOS and Android. Start from zero, no account needed.

Key idea

A pivot and 2 sides