Data Structures · Sorting

Quick sort

Quick sort picks one value, the pivot, and rearranges the array so that everything smaller is on its left and everything larger is on its right. The pivot is then in its final place, and the two sides are sorted the same way. On typical data it is one of the fastest sorts there is.

The idea

Like merge sort, quick sort is a divide and conquer algorithm, but it does its work before the recursive calls instead of after:

  1. Pick a pivot. This version uses the last element of the range.
  2. Partition. Rearrange the range so every value ≤ pivot comes first, then the pivot, then every value > pivot. The pivot is now exactly where it belongs in the sorted array.
  3. Recurse on the part left of the pivot and the part right of it. A range of 0 or 1 values is already sorted.

There is no merge step: once every pivot is in place, the array is sorted.

QuickSort(array, low, high):
    if low < high:
        pivotIndex = Partition(array, low, high)
        QuickSort(array, low, pivotIndex - 1)     // sort left part
        QuickSort(array, pivotIndex + 1, high)    // sort right part

Partition, step by step

The partition keeps two indexes. j scans the range from left to right. i marks the end of the "≤ pivot" region, which starts empty (i = low − 1). Whenever arr[j] ≤ pivot, the region grows by one: i moves right and arr[i] and arr[j] are swapped. At the end the pivot is swapped into position i + 1, just after the small values. This is called the Lomuto partition. During the scan the range always looks like this:

[ low ... i ]     [ i+1 ... j-1 ]    [ j ... high-1 ]    [ high ]
   ≤ pivot             > pivot          not yet seen        pivot

A worked example

Sorting {10, 80, 30, 90, 40, 50, 70}. Each row is one call to partition, showing the array after it finishes. Purple is the pivot just placed, blue cells are pivots placed earlier, and faded cells are outside the range.

Try it

The array

Pivot ≤ pivot > pivot Not yet seen In its final place

Call stack

    Variables

    What is happening

    main.cpp

      The array in main() changes to match what you sort.

      How much work does it do?

      The good case. If each pivot lands near the middle, every partition splits its range roughly in half. There are about log₂ n levels of calls, and the partitions on each level look at n values in total, so quick sort takes O(n log n) time. On random data this is what happens on average, with about 1.39 n log₂ n comparisons.

      The bad case. If the pivot is always the smallest or largest value, one side is empty and the other has everything else. Then the calls make n − 1, n − 2, … comparisons: n(n − 1) / 2 in total, which is O(n²). With the last element as pivot, this happens on input that is already sorted or reversed. Try the Already sorted preset and watch the call stack grow one frame per value.

      Memory. Quick sort sorts in place. The only extra memory is the call stack: O(log n) on average, but O(n) in the bad case.

      Choosing the pivot. The last element is simple, but it makes sorted input the worst case. Other common choices are the first element (same problem), a random element (the bad case becomes extremely unlikely), or the median of three: the middle value of the first, middle and last elements, which handles sorted input well.

      Comparisons made by this code (last-element pivot). Random is the average of 20 runs.

      Strengths and weaknesses

      Strengths
      • O(n log n) on average, and fast in practice: the inner loop is simple and scans memory in order.
      • Sorts in place; only the call stack uses extra memory.
      • The basis of the sort functions in many standard libraries.
      Weaknesses
      • O(n²) in the worst case, which a poor pivot rule makes easy to hit.
      • Not stable: partition swaps can move a value past an equal one. Try the Equal values preset.
      • Recursion depth can reach n in the worst case.

      Think first

      After the first partition of {10, 80, 30, 90, 40, 50, 70}, which value is guaranteed to be in its final place?

      The pivot, 70. Everything to its left is ≤ 70 and everything to its right is > 70, so it is exactly where the sorted array needs it, at index 4.

      Why is already-sorted input the worst case for this code?

      The pivot is the last element, which in sorted input is the largest value in the range. Every value is ≤ it, so the "> pivot" side is empty and the next call gets n − 1 values. The ranges shrink by only one each time.

      How does merge sort differ from quick sort in where the work happens?

      Merge sort splits without looking at the values and does its work afterwards, when it merges. Quick sort does its work first, in the partition, and needs nothing after the recursive calls.

      How would choosing a random pivot change the sorted-input case?

      A random pivot is usually near the middle of the range, whatever order the data is in, so sorted input behaves like random input: about n log n comparisons. Swap the random element into position high first, and the same partition code works unchanged.