Patterns: sorting
This review of sorting puts eight sorts' time, space and stability in one table, shows how to write comparisons for std::sort (lambdas, greater<int>(), several keys), and covers three patterns: sort then scan, your own order, and only the first k.
The last five lessons wrote eight sorts, yet at work you almost never write a sort yourself: std::sort is introsort, O(n log n) in the worst case, and faster than a hand-written quicksort. In exams, sorting questions usually test comparisons: which ones are stable, which are O(n log n) even in the worst case, what the array looks like after one pass. In interviews, most sorting questions fall into three patterns: sort, then scan once from left to right; sort by a rule of your own; only the first k, without sorting everything.
All the sorts in one table
| Sort | Average | Worst | Best | Extra space | Stable | One pass settles |
|---|---|---|---|---|---|---|
| Bubble | O(n²) | O(n²) | O(n) | O(1) | Yes | The largest one |
| Selection | O(n²) | O(n²) | O(n²) | O(1) | No | The smallest one |
| Insertion | O(n²) | O(n²) | O(n) | O(1) | Yes | None |
| Shell | about O(n^1.3) | O(n²) | O(1) | No | None | |
| Merge | O(n log n) | O(n log n) | O(n log n) | O(n) | Yes | None |
| Quick | O(n log n) | O(n²) | O(n log n) | O(log n) | No | The pivot |
| Counting | O(n + k) | O(n + k) | O(n + k) | O(k) | Yes | |
| Radix | O(d(n + r)) | O(d(n + r)) | O(n + r) | Yes |
To remember: the four unstable ones are selection, Shell, quick and heap (heap sort was in the trees chapter, and it's not stable either).
How to choose:
- Small data (a few dozen) or nearly sorted: insertion sort. It's what
std::sortuses for its final pass. - Must be stable, or it's a linked list: merge sort (in the STL,
stable_sortandlist::sort). - The usual case:
std::sort, quicksort with heap sort as a fallback, O(n log n) even in the worst case. - Integers in a small range: counting sort; a fixed number of digits: radix sort.
Which sorts are unstable? (You can pick more than one.)
Pattern 1: sort first, then scan once
Many problems are hard while the data is mixed up, and solved by one left-to-right scan once it's sorted: equal values end up next to each other (finding duplicates, removing them), overlapping intervals end up next to each other (merging intervals, meeting rooms), and two-sum can close in from both ends. Sorting is O(n log n), the scan O(n).
Merging intervals: sort by start, and each interval only has to be compared with the last one in out: if its start isn't past that one's end, they overlap and become one; otherwise start a new one.
iThe intervals are stored as pair<int, int>, and sort compares pairs by first, which is exactly by start; out.back() is the last one in out and can be changed directly.
1#include <iostream>2#include <vector>3#include <algorithm>4#include <utility>5using namespace std;6 7int main() {8 vector<pair<int, int>> v = {{8, 10}, {1, 3}, {15, 18}, {2, 6}, {9, 12}};9 sort(v.begin(), v.end()); // by start10 vector<pair<int, int>> out;11 for (const pair<int, int>& x : v) {12 if (!out.empty() && x.first <= out.back().second)13 out.back().second = max(out.back().second, x.second); // overlap: merge14 else15 out.push_back(x); // no overlap: start a new one16 }17 for (const pair<int, int>& x : out)18 cout << "[" << x.first << ", " << x.second << "] ";19 cout << "\n";20 return 0;21}
[1, 6] [8, 12] [15, 18]
Without sorting, each interval has to be compared with all the others, O(n²); once sorted, overlapping ones are always next to each other, and one scan is enough.
The intervals are already sorted by start: 1-4 3-5 6-8 8-9 11-12. With this stage's rule (merge when the start is no more than the end of the last one in out), what do you get?
Any duplicates in the array?
✓Sort it with sort first; any duplicates are then next to each other, so only neighbours need comparing. Print 1 (yes) or 0 (no).
0 1
1#include <iostream>2#include <vector>3#include <algorithm>4using namespace std;5 6bool has_dup(vector<int> a) {7 // sort it, then see whether any neighbours are equal8 return false;9}10 11int main() {12 vector<int> a = {8, 3, 5, 1, 9}, b = {4, 7, 2, 7, 1};13 cout << has_dup(a) << " " << has_dup(b) << "\n";14 return 0;15}
Pattern 2: your own order
The third argument of sort is the comparison: a function where cmp(x, y) returning true means x should come before y. The three most common forms:
- Nothing at all: uses
<, smallest first; greater<int>()(in<functional>): uses>, largest first;- A lambda:
[](const Student& x, const Student& y) { … }, compare however you like.
Sorting by several keys: highest score first, and equal scores by name from A to Z. The comparison looks at the score first, and if the scores differ, the score decides; only when they're equal does it compare names.
| Name | Score | Decided by |
|---|---|---|
| Dan | 95 | score |
| Amy | 90 | name |
| Cat | 90 | name |
| Bob | 85 | score |
1#include <iostream>2#include <vector>3#include <string>4#include <algorithm>5#include <functional>6using namespace std;7 8struct Student {9 string name;10 int score;11};12 13int main() {14 vector<int> a = {5, 2, 8, 1, 9, 3};15 sort(a.begin(), a.end(), greater<int>());16 for (int x : a) cout << x << " ";17 cout << "\n";18 19 vector<Student> s = {{"Cat", 90}, {"Bob", 85}, {"Dan", 95}, {"Amy", 90}};20 sort(s.begin(), s.end(), [](const Student& x, const Student& y) {21 if (x.score != y.score) return x.score > y.score; // higher score first22 return x.name < y.name; // same score: smaller name first23 });24 for (const Student& t : s)25 cout << t.name << " " << t.score << "\n";26 return 0;27}
9 8 5 3 2 1 Dan 95 Amy 90 Cat 90 Bob 85
Another way uses stability: sort by name first, then stable_sort by score, and equal scores keep the name order from the first pass. You can also write bool operator<(const Student& o) const in the struct, and from then on sort(s.begin(), s.end()) uses it by default.
Two traps. First, the comparison must be strict: with x.score >= y.score, two equal items each "come before" the other, std::sort's result is undefined, and with enough data it can even run out of bounds. Second, sort is not stable: comparing by score only, whether Amy or Cat comes first is anyone's guess; for a fixed order, put the name into the comparison too, or use stable_sort. C's qsort comparison returns negative, 0 or positive, and return x - y can overflow; a C++ comparison returns only a bool, so that problem doesn't exist.
Scores from high to low, and equal scores by name from A to Z. Fill in the two comparisons so the program shows Dan Amy Cat Bob.
1#include <iostream>2#include <vector>3#include <string>4#include <algorithm>5using namespace std;6 7struct Student {8 string name;9 int score;10};11 12int main() {13 vector<Student> s = {{"Bob", 85}, {"Amy", 90}, {"Dan", 95}, {"Cat", 90}};14 sort(s.begin(), s.end(), [](const Student& x, const Student& y) {15 if (x.score != y.score) return x.score y.score;16 return x.name y.name;17 });18 for (const Student& t : s)19 cout << t.name << " ";20 cout << "\n";21 return 0;22}
cmp(x, y) returning true means x goes before y. A higher score goes first, so x.score > y.score; a smaller name goes first, so x.name < y.name. Don't write >= or <=: the comparison must be strict, and two equal items can't both "go before each other".Sort by two conditions
✓Finish the lambda: younger first, and for the same age, smaller id first.
5 1 2 3 4
1#include <iostream>2#include <vector>3#include <algorithm>4using namespace std;5 6struct P {7 int id;8 int age;9};10 11int main() {12 vector<P> p = {{3, 30}, {1, 25}, {4, 30}, {2, 25}, {5, 18}};13 sort(p.begin(), p.end(), [](const P& x, const P& y) {14 // compare age first, then id when equal15 return false;16 });17 for (const P& t : p)18 cout << t.id << " ";19 cout << "\n";20 return 0;21}
Pattern 3: only the first k
To find the k-th smallest, sorting everything is O(n log n). Quickselect borrows quicksort's partition: after one partition, the pivot is at index m. If m is exactly k, done; if k is on the left, search only the left, and if it's on the right, only the right. Each time it goes one way only, O(n) on average.
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) swap(a[i++], a[j]);10 swap(a[i], a[hi]);11 return i;12}13 14// the k-th smallest (k counts from 0)15int select_k(vector<int>& a, int k) {16 int lo = 0, hi = a.size() - 1;17 while (true) {18 int m = partition(a, lo, hi);19 if (m == k) return a[m];20 if (k < m) hi = m - 1;21 else lo = m + 1;22 }23}24 25int main() {26 vector<int> a = {7, 2, 9, 4, 3, 8, 5};27 cout << "3rd smallest: " << select_k(a, 2) << "\n";28 for (int x : a) cout << x << " ";29 cout << "\n";30 return 0;31}
3rd smallest: 4 2 3 4 5 9 8 7
The array printed is 2 3 4 5 9 8 7: the 3rd smallest, 4, is at index 2, everything on its left is smaller and everything on its right larger, but the right part isn't sorted. "The median", "the k-th largest", "the k smallest" all use this pattern; the other common answer is a heap of size k, O(n log k), which also works when the data streams in one item at a time.
Quickselect
✓partition is given. Finish select_k: after partitioning the pivot is at m; return if it equals k, otherwise go on into one side only.
3 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) swap(a[i++], a[j]);10 swap(a[i], a[hi]);11 return i;12}13 14int select_k(vector<int> a, int k) {15 int lo = 0, hi = a.size() - 1;16 // loop: m = partition; m == k returns a[m]; k < m goes left, otherwise right17 return -1;18}19 20int main() {21 vector<int> a = {12, 3, 5, 7, 4, 19, 26};22 cout << select_k(a, 0) << " " << select_k(a, 3) << "\n";23 return 0;24}
With the STL
All three patterns are ready-made in the STL:
1#include <iostream>2#include <vector>3#include <queue>4#include <algorithm>5#include <functional>6using namespace std;7 8int main() {9 vector<int> a = {58, 91, 72, 66, 99, 43, 87, 95, 60, 77};10 int k = 3;11 12 // the k largest, sorted: sort only the first k13 vector<int> b = a;14 partial_sort(b.begin(), b.begin() + k, b.end(), greater<int>());15 cout << "partial_sort: ";16 for (int i = 0; i < k; i++) cout << b[i] << " ";17 cout << "\n";18 19 // the k-th largest: nth_element is quickselect20 vector<int> c = a;21 nth_element(c.begin(), c.begin() + (k - 1), c.end(), greater<int>());22 cout << "largest no. " << k << ": " << c[k - 1] << "\n";23 24 // the k largest, arriving one by one: a size-k min-heap, kick out the smallest when too many25 priority_queue<int, vector<int>, greater<int>> q;26 for (int x : a) {27 q.push(x);28 if ((int)q.size() > k) q.pop();29 }30 cout << "in the heap: ";31 while (!q.empty()) { cout << q.top() << " "; q.pop(); }32 cout << "\n";33 34 // remove duplicates after sorting: equal ones are next to each other35 vector<int> d = {3, 1, 3, 2, 1, 3};36 sort(d.begin(), d.end());37 d.erase(unique(d.begin(), d.end()), d.end());38 cout << "unique: ";39 for (int x : d) cout << x << " ";40 cout << "\n";41 return 0;42}
partial_sort: 99 95 91 largest no. 3: 91 in the heap: 91 95 99 unique: 1 2 3
Inside partial_sort is a heap: the first k become a heap, later ones better than the top are swapped in, and at the end those k are sorted. priority_queue is a min-heap only with greater<int> (the default is a max-heap), and it pops smallest first. unique only moves adjacent duplicates to the back and returns the new end, so sort first, then erase that tail.
| To do | Call | Cost |
|---|---|---|
| Sort everything | sort(b, e, cmp) | O(n log n), not stable |
| Sort, equal ones keep their order | stable_sort(b, e, cmp) | O(n log n), O(n) extra space |
| The first k sorted | partial_sort(b, b + k, e, cmp) | O(n log k) |
| Only the k-th one | nth_element(b, b + k, e, cmp) | O(n) on average |
| The k largest of a stream | a size-k priority_queue<int, vector<int>, greater<int>> | O(n log k), O(k) memory |
| Remove duplicates | sort + unique + erase | O(n log n) |
In interviews: Start with the problems that "get easy once sorted": merging intervals, meeting rooms, two-sum (two pointers), finding duplicates, O(n log n). For several keys, the lambda compares the main key first and returns if they differ, and only then the next key. For the k-th largest, answer a heap at O(n log k) first, then nth_element at O(n) on average. Asked "can the comparison use <=?": no, it must be a strict weak ordering, otherwise std::sort is undefined behaviour.
unique straight away, without sorting first. What does the program print?
1#include <iostream>2#include <vector>3#include <algorithm>4using namespace std;5 6int main() {7 vector<int> a = {1, 3, 3, 1, 1, 2};8 a.erase(unique(a.begin(), a.end()), a.end());9 cout << a.size() << "\n";10 return 0;11}
unique only removes neighbouring repeats: 1 3 3 1 1 2 becomes 1 3 1 2, so 4 are left. The 1s that aren't next to each other both stay. To really remove duplicates, sort first to get 1 1 1 2 3 3, then unique + erase, which leaves the three numbers 1 2 3.Summary
Three sorting patterns
- The four unstable: selection, Shell, quick, heap; O(n log n) even at worst: merge, heap (and std::sort)
- Sort, then scan once: merging intervals, finding duplicates, removing them (sort + unique)
- Your own order: the lambda compares the main key, then the next, and must be strict; greater<int>() for largest first; stable_sort when you need stable
- Only the first k: quickselect / nth_element O(n) on average; partial_sort and a size-k heap O(n log k)
1sort(s.begin(), s.end(), [](const Student& x, const Student& y) {2 if (x.score != y.score) return x.score > y.score;3 return x.name < y.name;4});5nth_element(a.begin(), a.begin() + k, a.end());
Chapter 7 quick check
5 questions: one round of bubble and selection, one Shell pass, quicksort's compares, merge sort's calls, one radix pass. Work out what each prints first, then pick an option.
Bubble sort and selection sort each do just one round on 4 3 2 1. What does it print?
1#include <iostream>2#include <vector>3#include <utility>4using namespace std;5 6int main() {7 vector<int> a = {4, 3, 2, 1}, b = {4, 3, 2, 1};8 for (int j = 0; j < 3; j++) // one round of bubble9 if (a[j] > a[j + 1]) swap(a[j], a[j + 1]);10 int m = 0; // one round of selection11 for (int j = 1; j < 4; j++)12 if (b[j] < b[m]) m = j;13 swap(b[0], b[m]);14 for (int x : a) cout << x << " ";15 cout << "| ";16 for (int x : b) cout << x << " ";17 cout << "\n";18 return 0;19}
After Shell sort's gap-2 pass over 9 8 7 6 5 4, what does it print?
1#include <iostream>2#include <vector>3using namespace std;4 5int main() {6 vector<int> a = {9, 8, 7, 6, 5, 4};7 int n = a.size(), gap = 2;8 for (int i = gap; i < n; i++) {9 int key = a[i], j = i - gap;10 while (j >= 0 && a[j] > key) {11 a[j + gap] = a[j];12 j -= gap;13 }14 a[j + gap] = key;15 }16 for (int x : a) cout << x << " ";17 cout << "\n";18 return 0;19}
Quicksort with the last one as the pivot sorts 0 to 9, already sorted. How many compares?
1#include <iostream>2#include <vector>3#include <utility>4using namespace std;5 6long long cmps = 0;7 8void qs(vector<int>& a, int lo, int hi) {9 if (lo >= hi) return;10 int p = a[hi], i = lo;11 for (int j = lo; j < hi; j++) {12 cmps++;13 if (a[j] < p) swap(a[i++], a[j]);14 }15 swap(a[i], a[hi]);16 qs(a, lo, i - 1);17 qs(a, i + 1, hi);18}19 20int main() {21 vector<int> a(10);22 for (int i = 0; i < 10; i++) a[i] = i;23 qs(a, 0, 9);24 cout << cmps << "\n";25 return 0;26}
Merge sort on 6 numbers: how many times is merge_sort called in all?
1#include <iostream>2using namespace std;3 4int calls = 0;5 6void ms(int lo, int hi) {7 calls++;8 if (lo >= hi) return;9 int mid = (lo + hi) / 2;10 ms(lo, mid);11 ms(mid + 1, hi);12}13 14int main() {15 ms(0, 5);16 cout << calls << "\n";17 return 0;18}
Radix sort's first pass: one stable counting sort by the ones digit. What does it print?
1#include <iostream>2#include <vector>3using namespace std;4 5int main() {6 vector<int> a = {21, 12, 31, 22};7 int n = a.size();8 vector<int> out(n), cnt(10, 0);9 for (int x : a) cnt[x % 10]++;10 for (int d = 1; d < 10; d++) cnt[d] += cnt[d - 1];11 for (int i = n - 1; i >= 0; i--)12 out[--cnt[a[i] % 10]] = a[i];13 for (int x : out) cout << x << " ";14 cout << "\n";15 return 0;16}