Quicksort
Quicksort partitions around a pivot, smaller values left and larger right, which puts the pivot in its final place, then sorts each side: O(n log n) on average, O(n²) on sorted input unless the pivot is random (mt19937); std::sort builds on it.
Merge sort recurses first and merges after, and it needs a temporary array. Quicksort goes the other way: first one partition splits the array into "all smaller than the pivot" and "all larger than the pivot", and the pivot stands in its final place; then it recurses on the two parts. No merging, no extra array, and in practice it is usually the fastest comparison sort. Inside C++'s std::sort, it does most of the work.
Partition: smaller than the pivot goes left
Take the last number as the pivot p. Index i is the right edge of the "smaller than p" region: j scans left to right, and each time it finds something smaller than p it swaps it with a[i] and moves i one step right. After the scan, swap p into a[i]: everything to its left is smaller, everything to its right is not smaller.
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 only a few variables. The swap is std::swap from <utility>, and the vector is passed by reference, so the original is the one that changes.
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 at the end, and return i.
2 3 1 6 9 8 7
1#include <iostream>2#include <vector>3#include <utility>4using namespace std;5 6int partition(vector<int>& a, int lo, int hi) {7 int p = a[hi], i = lo;8 // j scans lo to hi - 1: if a[j] < p, swap it with a[i], i++9 // at the end swap the pivot with a[i]10 return i;11}12 13int main() {14 vector<int> a = {9, 3, 7, 1, 8, 6};15 int m = partition(a, 0, 5);16 cout << m << "\n";17 for (int x : a)18 cout << x << " ";19 cout << "\n";20 return 0;21}
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 <iostream>2#include <vector>3#include <utility>4using namespace std;5 6int partition(vector<int>& a, int lo, int hi) {7 int p = a[hi], i = lo;8 for (int j = lo; j < hi; j++)9 if (a[j] < p) {10 swap(a[i], a[j]);11 i++;12 }13 swap(a[i], a[hi]);14 return i;15}16 17void quick_sort(vector<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 main() {25 vector<int> a = {4, 7, 2, 6, 1, 5};26 quick_sort(a, 0, a.size() - 1);27 for (int x : a)28 cout << x << " ";29 cout << "\n";30 return 0;31}
1 2 4 5 6 7
Fill in the two recursive calls so the program prints 1 2 4 5 6 7.
1#include <iostream>2#include <vector>3#include <utility>4using namespace std;5 6int partition(vector<int>& a, int lo, int hi) {7 int p = a[hi], i = lo;8 for (int j = lo; j < hi; j++)9 if (a[j] < p) {10 swap(a[i], a[j]);11 i++;12 }13 swap(a[i], a[hi]);14 return i;15}16 17void quick_sort(vector<int>& a, int lo, int hi) {18 if (lo >= hi) return;19 int m = partition(a, lo, hi);20 quick_sort(a, lo, );21 quick_sort(a, , hi);22}23 24int main() {25 vector<int> a = {4, 7, 2, 6, 1, 5};26 quick_sort(a, 0, a.size() - 1);27 for (int x : a)28 cout << x << " ";29 cout << "\n";30 return 0;31}
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 includes the pivot).
1 2 3 5 7 8 9
1#include <iostream>2#include <vector>3#include <utility>4using namespace std;5 6int partition(vector<int>& a, int lo, int hi) {7 int p = a[hi], i = lo;8 for (int j = lo; j < hi; j++)9 if (a[j] < p) {10 swap(a[i], a[j]);11 i++;12 }13 swap(a[i], a[hi]);14 return i;15}16 17void quick_sort(vector<int>& a, int lo, int hi) {18 // return if lo >= hi; m = partition; left lo..m-1, right m+1..hi19}20 21int main() {22 vector<int> a = {5, 9, 1, 7, 3, 8, 2};23 quick_sort(a, 0, 6);24 for (int x : a)25 cout << x << " ";26 cout << "\n";27 return 0;28}
Average O(n log n), worst O(n²)
If the pivot is roughly in the middle every time, each level cuts the problem in half, and it's O(n log n) like merge sort. But if the pivot is the largest or the smallest every time, one partition settles only one number, and it falls to n + (n − 1) + … = O(n²). And the most common input sets this off: an array that's already sorted. Taking the last one as the pivot, it's the largest, everything smaller is on the left, and the right is empty.
Count the compares. In this program, shuffle first mixes up 0 to 399 (mt19937 g(42) fixes the seed, so the shuffle is the same every run) and sorts it once; then it sorts the already sorted array again:
1#include <iostream>2#include <vector>3#include <random>4#include <algorithm>5#include <utility>6using namespace std;7 8long long cmps = 0;9 10int partition(vector<int>& a, int lo, int hi) {11 int p = a[hi], i = lo;12 for (int j = lo; j < hi; j++) {13 cmps++;14 if (a[j] < p) { swap(a[i], a[j]); i++; }15 }16 swap(a[i], a[hi]);17 return i;18}19 20void quick_sort(vector<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() {28 int n = 400;29 vector<int> a(n);30 for (int i = 0; i < n; i++) a[i] = i;31 mt19937 g(42);32 shuffle(a.begin(), a.end(), g);33 cmps = 0; quick_sort(a, 0, n - 1);34 cout << "400 shuffled: " << cmps << " compares\n";35 cmps = 0; quick_sort(a, 0, n - 1); // a is sorted now36 cout << "400 sorted: " << cmps << " compares\n";37 return 0;38}
400 shuffled: 3735 compares 400 sorted: 79800 compares
The sorted run is exactly 399 + 398 + … + 1 = 79800 compares, more than twenty times the shuffled run's 3735; and the recursion goes 400 levels deep. With n at a million, that's the difference between "a few milliseconds" and "tens of minutes", plus a stack overflow.
This is quicksort's recursion on a sorted array (the pivot is the largest every time, leaving only the left part up to hi − 1). With 10 numbers, how many levels deep does the recursion go?
1#include <iostream>2using namespace std;3 4int depth = 0, best = 0;5 6void qs(int lo, int hi) {7 if (lo >= hi) return;8 depth++;9 if (depth > best) best = depth;10 qs(lo, hi - 1);11 depth--;12}13 14int main() {15 qs(0, 9);16 cout << best << "\n";17 return 0;18}
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. Then whatever the input looks like, the chance of hitting the worst case is tiny, and the expected cost is O(n log n). In C++ random numbers come from <random>: mt19937 g(42) is a random number engine (42 is the seed; fixed, every run gives the same result), uniform_int_distribution<int> d(lo, hi) turns it into integers spread evenly over lo..hi, and d(g) takes one.
1#include <iostream>2#include <vector>3#include <random>4#include <utility>5using namespace std;6 7long long cmps = 0;8mt19937 g(42);9 10int partition(vector<int>& a, int lo, int hi) {11 uniform_int_distribution<int> d(lo, hi);12 swap(a[d(g)], a[hi]); // a random position goes to the end, then as usual13 int p = a[hi], i = lo;14 for (int j = lo; j < hi; j++) {15 cmps++;16 if (a[j] < p) { swap(a[i], a[j]); i++; }17 }18 swap(a[i], a[hi]);19 return i;20}21 22void quick_sort(vector<int>& a, int lo, int hi) {23 if (lo >= hi) return;24 int m = partition(a, lo, hi);25 quick_sort(a, lo, m - 1);26 quick_sort(a, m + 1, hi);27}28 29int main() {30 int n = 400;31 vector<int> a(n);32 for (int i = 0; i < n; i++) a[i] = i;33 cmps = 0; quick_sort(a, 0, n - 1);34 cout << "400 sorted: " << cmps << " compares\n";35 for (int i = 0; i < n; i++) a[i] = n - i;36 cmps = 0; quick_sort(a, 0, n - 1);37 cout << "400 reversed: " << cmps << " compares\n";38 return 0;39}
400 sorted: 3402 compares 400 reversed: 3548 compares
Sorted input drops from 79800 compares to 3402, reversed is also a little over three thousand, about the same as shuffled input. Another common choice is "median of three": take the middle one of a[lo], a[mid] and a[hi] as the pivot. No random numbers, and sorted input gets the exact middle.
| Average | Worst | Extra space | Stable | |
|---|---|---|---|---|
| Quicksort | O(n log n) | O(n²) (sorted input, bad pivots) | O(log n) recursion stack | No |
| Merge sort | O(n log n) | O(n log n) | O(n) | Yes |
In exams: "When is quicksort slowest?" Answer: "when the input is already sorted or reversed". "How many elements does one partition put in their final place?" Answer: 1 (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?
The random position must be able to land on every place from lo to hi (hi included). What goes as the second number of uniform_int_distribution?
1uniform_int_distribution<int> d(lo, );2swap(a[d(g)], a[hi]);3int p = a[hi], i = lo;
uniform_int_distribution<int> d(a, b) gives whole numbers from a to b, both ends included (unlike rand() % k, which only reaches k − 1). So hi is right. With hi - 1 it never picks a[hi]; hi + 1 can land outside the part, out of bounds; hi - lo is the part's length minus 1, not an index.With the STL
Day to day you don't write quicksort: sort(a.begin(), a.end()) from <algorithm> does it, and a third argument gives the comparison, such as greater<int>() for largest first. Inside it is introsort:
- The body is quicksort, with the pivot chosen by "median of three";
- When the recursion goes deeper than about 2 log₂ n, the input is a bad one, and that part switches to heap sort, so the worst case is O(n log n) too;
- Parts of 16 or fewer are left for a final pass of insertion sort, which is fastest on small arrays.
nth_element is another use of quicksort: after one partition it only goes on into the side where the k-th one is and ignores the other. It puts the k-th smallest at index k, nothing larger on its left and nothing smaller on its right, in O(n) on average.
1#include <iostream>2#include <vector>3#include <algorithm>4#include <functional>5using namespace std;6 7int main() {8 vector<int> a = {4, 7, 2, 6, 1, 5};9 sort(a.begin(), a.end()); // smallest first10 for (int x : a) cout << x << " ";11 cout << "\n";12 sort(a.begin(), a.end(), greater<int>()); // largest first13 for (int x : a) cout << x << " ";14 cout << "\n";15 16 // count std::sort's compares: sorting 400 that are sorted17 vector<int> b(400);18 for (int i = 0; i < 400; i++) b[i] = i;19 long long cmps = 0;20 sort(b.begin(), b.end(), [&cmps](int x, int y) {21 cmps++;22 return x < y;23 });24 cout << "std::sort on 400 sorted: " << cmps << " compares\n";25 26 // nth_element: only the median goes to the middle27 vector<int> c = {9, 3, 7, 1, 8, 6, 2};28 nth_element(c.begin(), c.begin() + 3, c.end());29 cout << "median: " << c[3] << "\n";30 return 0;31}
1 2 4 5 6 7 7 6 5 4 2 1 std::sort on 400 sorted: 3669 compares median: 6
The comparison is a lambda, and [&cmps] lets it change the counter outside. On 400 sorted numbers, std::sort makes only a little over three thousand compares: no slide to O(n²).
| Call | What it does | Cost |
|---|---|---|
sort(b, e) | Sorts everything, not stable | O(n log n), worst case too |
sort(b, e, greater<int>()) | Largest first | Same |
stable_sort(b, e) | Sorts everything, equal ones keep their order (merge sort) | O(n log n), O(n) extra space |
nth_element(b, b + k, e) | k-th smallest at index k, the two sides unsorted | O(n) on average |
In interviews: "What sort is std::sort?" Answer introsort: quicksort + heap sort when the recursion gets too deep + insertion sort on small parts, worst case O(n log n), not stable; use stable_sort when you need stable. "What happens to a hand-written quicksort on sorted input?" Answer O(n²) and n levels of recursion, fixed by a random pivot or median of three. The comparison must be "strictly less": writing <= is undefined behaviour, and std::sort may run past the end.
nth_element puts the k-th smallest at index k. What does the program print?
1#include <iostream>2#include <vector>3#include <algorithm>4using namespace std;5 6int main() {7 vector<int> c = {9, 3, 7, 1, 8, 6, 2};8 nth_element(c.begin(), c.begin() + 2, c.end());9 cout << c[2] << "\n";10 return 0;11}
nth_element only promises that c[2] is the number that belongs there, with nothing bigger to its left and nothing smaller to its right; the order on each side is not fixed, so don't guess what the other places hold.You hand std::sort a million numbers that are already sorted. How long can it take at worst?
std::sort is introsort: it picks the pivot by median of three, so sorted input already gives a middle pivot; and if it does meet bad input, it switches to heap sort once the recursion is deeper than about 2 log₂ n. So its worst case is O(n log n); it never drags down to O(n²) like a hand-written "last number as pivot" quicksort.Summary
Quicksort: one partition, the pivot is placed, recurse on both sides
- Partition: pivot a[hi], smaller ones swapped left, the pivot swapped to i at the end, O(n)
- Average O(n log n); falls to O(n²) on sorted input, when the pivot is always the largest or smallest
- A random pivot (mt19937 + uniform_int_distribution) or median of three; not stable; O(log n) recursion stack
- STL: sort is introsort, worst case O(n log n); nth_element goes one side only, O(n) on average
1int p = a[hi], i = lo;2for (int j = lo; j < hi; j++)3 if (a[j] < p) swap(a[i++], a[j]);4swap(a[i], a[hi]);5sort(a.begin(), a.end());