Quicksort
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.
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]);
One partition is one scan: O(n), with just a few variables.
Using this step's partition (the last number is the pivot), what does 3 8 1 9 2 6 look like after one partition?
[1 2 3 6 8 9].After one partition, how many numbers are known to be in their final place?
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.
2 3 1 6 9 8 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 // 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}
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:
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}
1 2 4 5 6 7
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 the 4 lines of quick_sort in order so the program prints 1 2 4 5 6 7.
if (lo >= hi) return;quick_sort(a, lo, m - 1);int m = partition(a, lo, hi);quick_sort(a, m + 1, hi);
1 2 4 5 6 7
Write quick_sort
✓partition is given. Finish the recursion: partition, then recurse on the parts left and right of the pivot (neither including it).
1 2 3 5 7 8 9
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}
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.
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}
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.
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}
With the last number as the pivot, which inputs make quicksort slow down to O(n²)? (You can pick more than one.)
a[j] < p is never true, the pivot is swapped to the far left and n − 1 numbers are left on its right, just as slow. In a shuffled array the pivot usually lands somewhere near the middle.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;
| Average | Worst | Extra space | Stable | |
|---|---|---|---|---|
| Quicksort | O(n log n) | O(n²) (sorted input, poor pivots) | O(log n) recursion stack | not stable |
| Merge sort | O(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.
"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?
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;
rand() % k gives 0 to k − 1. The part holds hi − lo + 1 numbers, so it has to be % (hi - lo + 1). With hi - lo, a[hi] is never picked; with hi, r can land outside the part.Summary
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]);