Kodewick
Start learning →
Quicksort42 / 50

Quicksort

Lesson 42 of 50 · Part 8 · Sorting · about 18 minutes

Quicksort partitions the array around a pivot, smaller values to its left and the rest to its right, which puts the pivot in its final place, then recurses on both sides: O(n log n) on average, O(n²) on sorted input, which a random pivot avoids.

Merge sort recurses first and merges after, with a second array. Quicksort does it the other way round: one partition splits the array into "all smaller than the pivot" and "all at least the pivot", which puts the pivot in its final place; then it recurses on the two parts. No merging, no extra array, and in practice usually the fastest comparison sort; C's standard qsort is named after it.

Partition: the smaller ones to the left

Take the last number as the pivot p. Pointer i is the right edge of "the part smaller than p": j scans left to right, and each number smaller than p is swapped with a[i] and i moves on. When the scan is done, p is swapped into a[i]: everything to its left is smaller, everything to its right isn't.

acomparisons 0 · swaps 0472615012345
1int p = a[hi], i = lo;2for (int j = lo; j < hi; j++)3    if (a[j] < p) {4        swap(&a[i], &a[j]);5        i++;6    }7swap(&a[i], &a[hi]);

Partitioning 4 7 2 6 1 5 around the last number, 5: those smaller than 5 are swapped to the left, and 5 lands at index 3, its place in the sorted array

One partition is one scan: O(n), with just a few variables.

Choose one

Using this step's partition (the last number is the pivot), what does 3 8 1 9 2 6 look like after one partition?

Choose one

After one partition, how many numbers are known to be in their final place?

Exercise 1

Write partition

Finish the partition: with a[hi] as the pivot, swap the smaller ones to the left, put the pivot at i, and return i.

It should print
2
3 1 6 9 8 7
exercise1.c
1#include <stdio.h>2 3void swap(int *x, int *y) { int t = *x; *x = *y; *y = t; }4 5int partition(int a[], int lo, int hi) {6    int p = a[hi], i = lo;7    // j from lo to hi - 1: if a[j] < p, swap it with a[i] and i++8    // then swap the pivot with a[i]9    return i;10}11 12int main(void) {13    int a[] = {9, 3, 7, 1, 8, 6};14    int m = partition(a, 0, 5);15    printf("%d\n", m);16    for (int i = 0; i < 6; i++)17        printf("%d ", a[i]);18    printf("\n");19    return 0;20}
Output
Press Run or Ctrl+Enter

Recursion: partition each side again

One partition puts just one number in place, the pivot; the part to its left and the part to its right are still jumbled. So you partition each part again: each one gets its own pivot into place, and the parts keep getting shorter. A part with fewer than two numbers (lo >= hi) is already sorted: that is where the recursion stops. Neither part includes the pivot: the left one is lo..m-1, the right one m+1..hi.

Run it and watch, step by step, how it sorts 4 7 2 6 1 5:

main.c
1#include <stdio.h>2 3void swap(int *x, int *y) {4    int t = *x;5    *x = *y;6    *y = t;7}8 9int partition(int a[], int lo, int hi) {10    int p = a[hi], i = lo;11    for (int j = lo; j < hi; j++)12        if (a[j] < p) {13            swap(&a[i], &a[j]);14            i++;15        }16    swap(&a[i], &a[hi]);17    return i;18}19 20void quick_sort(int a[], int lo, int hi) {21    if (lo >= hi) return;22    int m = partition(a, lo, hi);23    quick_sort(a, lo, m - 1);24    quick_sort(a, m + 1, hi);25}26 27int main(void) {28    int a[] = {4, 7, 2, 6, 1, 5};29    quick_sort(a, 0, 5);30    for (int i = 0; i < 6; i++)31        printf("%d ", a[i]);32    printf("\n");33    return 0;34}
Output
1 2 4 5 6 7 
Fill inTap one to fill a blank; tap a blank to take it back

Fill in the two recursive calls so the program prints 1 2 4 5 6 7.

1#include <stdio.h>2 3void swap(int *x, int *y) { int t = *x; *x = *y; *y = t; }4 5int partition(int a[], int lo, int hi) {6    int p = a[hi], i = lo;7    for (int j = lo; j < hi; j++)8        if (a[j] < p) {9            swap(&a[i], &a[j]);10            i++;11        }12    swap(&a[i], &a[hi]);13    return i;14}15 16void quick_sort(int a[], int lo, int hi) {17    if (lo >= hi) return;18    int m = partition(a, lo, hi);19    quick_sort(a, lo, );20    quick_sort(a, , hi);21}22 23int main(void) {24    int a[] = {4, 7, 2, 6, 1, 5};25    quick_sort(a, 0, 5);26    for (int i = 0; i < 6; i++)27        printf("%d ", a[i]);28    printf("\n");29    return 0;30}
Put in orderDrag, or use the arrows

Put the 4 lines of quick_sort in order so the program prints 1 2 4 5 6 7.

  1. if (lo >= hi) return;
  2. quick_sort(a, lo, m - 1);
  3. int m = partition(a, lo, hi);
  4. quick_sort(a, m + 1, hi);
Should print
1 2 4 5 6 7
Exercise 2

Write quick_sort

partition is given. Finish the recursion: partition, then recurse on the parts left and right of the pivot (neither including it).

It should print
1 2 3 5 7 8 9
exercise2.c
1#include <stdio.h>2 3void swap(int *x, int *y) { int t = *x; *x = *y; *y = t; }4 5int partition(int a[], int lo, int hi) {6    int p = a[hi], i = lo;7    for (int j = lo; j < hi; j++)8        if (a[j] < p) {9            swap(&a[i], &a[j]);10            i++;11        }12    swap(&a[i], &a[hi]);13    return i;14}15 16void quick_sort(int a[], int lo, int hi) {17    // lo >= hi: return; m = partition; left lo..m-1, right m+1..hi18}19 20int main(void) {21    int a[] = {5, 9, 1, 7, 3, 8, 2};22    quick_sort(a, 0, 6);23    for (int i = 0; i < 7; i++)24        printf("%d ", a[i]);25    printf("\n");26    return 0;27}
Output
Press Run or Ctrl+Enter

O(n log n) on average, O(n²) at worst

If the pivot lands near the middle each time, every level halves the problem: O(n log n), like merge sort. But if the pivot is always the largest or the smallest, each partition places only one number, and it sinks to n + (n − 1) + … = O(n²). And the most ordinary input triggers it: an array already sorted, where the last number, the pivot, is always the largest.

0..4

Sorted 1 2 3 4 5: the pivot is always the biggest, the right part is empty, and all that is left is the left part, one number shorter. Each node is the index range being sorted; the recursion tree turns into a slanted line
main.c
1#include <stdio.h>2 3long long cmps = 0;4 5void swap(int *x, int *y) { int t = *x; *x = *y; *y = t; }6 7int partition(int a[], int lo, int hi) {8    int p = a[hi], i = lo;9    for (int j = lo; j < hi; j++) {10        cmps++;11        if (a[j] < p) { swap(&a[i], &a[j]); i++; }12    }13    swap(&a[i], &a[hi]);14    return i;15}16 17void quick_sort(int a[], int lo, int hi) {18    if (lo >= hi) return;19    int m = partition(a, lo, hi);20    quick_sort(a, lo, m - 1);21    quick_sort(a, m + 1, hi);22}23 24int a[400];25 26int main(void) {27    int n = 400;28    unsigned s = 1;29    for (int i = 0; i < n; i++) { s = s * 1103515245 + 12345; a[i] = s % 1000; }30    cmps = 0; quick_sort(a, 0, n - 1);31    printf("400 shuffled: %lld comparisons\n", cmps);32    for (int i = 0; i < n; i++) a[i] = i;33    cmps = 0; quick_sort(a, 0, n - 1);34    printf("400 sorted:   %lld comparisons\n", cmps);35    return 0;36}
Output
400 shuffled: 3542 comparisons
400 sorted:   79800 comparisons

The sorted run is exactly 399 + 398 + … + 1 = 79800, over twenty times the shuffled one; the recursion is also 400 deep. With n a million, it's the difference between milliseconds and tens of minutes, plus a stack overflow.

Guess the outputA wrong guess is fine

This is quicksort's recursion on a sorted array (the pivot always the largest, leaving only lo..hi − 1). For 10 numbers, how deep does it go?

1#include <stdio.h>2 3int depth = 0, best = 0;4 5void qs(int lo, int hi) {6    if (lo >= hi) return;7    depth++;8    if (depth > best) best = depth;9    qs(lo, hi - 1);10    depth--;11}12 13int main(void) {14    qs(0, 9);15    printf("%d\n", best);16    return 0;17}
Choose allPick all that apply

With the last number as the pivot, which inputs make quicksort slow down to O(n²)? (You can pick more than one.)

A random pivot

The fix is simple: don't always take the last one. Before partitioning, pick a random position, swap it with a[hi], and partition as usual. Whatever the input, the worst case becomes vanishingly unlikely, and the expected time is O(n log n). Another common choice is "median of three": the middle of a[lo], a[mid] and a[hi].

1int r = lo + rand() % (hi - lo + 1);   // a random position2swap(&a[r], &a[hi]);                   // to the end, then as usual3int p = a[hi], i = lo;
AverageWorstExtra spaceStable
QuicksortO(n log n)O(n²) (sorted input, poor pivots)O(log n) recursion stacknot stable
Merge sortO(n log n)O(n log n)O(n)stable

In exams: "when is quicksort slowest": already sorted or reversed input; "how many elements does one partition place": one, the pivot. Quicksort is the fastest internal sort on average, but not stable.

Choose one

"Median of three" looks at a[lo], a[mid] and a[hi] and takes the middle one as the pivot. For the sorted 1 2 3 4 5 6 7, which pivot does it pick?

Fill inTap one to fill a blank; tap a blank to take it back

When picking a random position, r has to be able to land on every position from lo to hi (hi included). What goes after the %?

1int r = lo + rand() % ();2swap(&a[r], &a[hi]);3int p = a[hi], i = lo;

Summary

Take-away

Quicksort: one partition places the pivot, then both sides

  • Partition: pivot a[hi], the smaller swapped left, the pivot into i at the end, O(n)
  • O(n log n) on average; O(n²) on sorted input, when the pivot is always an extreme
  • Random pivot or median of three; not stable; O(log n) recursion stack
1p = a[hi]; i = lo;2for (j = lo; j < hi; j++)3    if (a[j] < p) swap(&a[i++], &a[j]);4swap(&a[i], &a[hi]);