Partition around a pivot and avoid the quadratic worst case.
Use it when you must sort in place, or split a list around a value, or find the k-th smallest value. Signal words: in place, split around a reference, the k-th smallest, many equal values, the list arrives sorted.
Start a range of zero or one value is sorted. Otherwise pick a pivot, preferably at random.
Step partition the range around the pivot. Sort the smaller side by recursion, and loop on the larger side.
Stop when the range holds zero or one value. For quick select, stop when the target place falls on the pivot's place.
It does not keep equal values in their order, and it has a worst case of n² comparisons that a random pivot makes very unlikely.
Cost: O(n log n) expected time, O(n²) in the worst case, and O(log n) extra space for the recursion when the smaller side goes first.
In this lesson you write the partition step, in two versions, and you build quick sort on it. You learn why one bad pivot rule turns an n log n sort into an n² sort. You also learn how a random pivot and a shallow recursion remove that risk. You also use the same partition to find the k-th smallest value without a full sort.
You work on the ride-hailing app. Pending requests wait in a list, and the dispatcher serves them by waiting time, shortest first. The server holds the list and little more, so a second copy of 100,000 requests does not fit.
The list comes in the order the requests arrived. So the longest waits are first, and the list is in reverse order of what the dispatcher needs. Comparing two waits takes about 1 microsecond.
Your team lead says: Sort the list in place before the next dispatch. Tell me what it costs when the list arrives in this order.
Here is a short test: seven requests with waits of 31, 12, 44, 7, 25, 38 and 20 seconds. Sorted, they read 7, 12, 20, 25, 31, 38, 44.
So the task is this: sort the waits in place, and make the cost safe whatever the order of the list.
A crowd waits at a ticket gate. You pick one person as the reference. Everyone who has waited less than the reference steps to the left, and everyone else steps to the right. The reference stands in the gap.
Now the reference is in the right place for the whole queue, and nobody on the left needs to be compared with anybody on the right. You repeat with each side. The reference is the pivot, and the split is a partition.
Split a queue around one person: those who waited less go left, the rest go right, and the reference stands in the gap.
Before you write code, split the seven waits by hand around the last value. It shows what one partition does.
Solve it by hand: Seven waits: split them around the last value. The hand-solve sheet loads in your browser.
You take the last value, 20, as the pivot. You scan the other values from the left. Each value less than 20 goes into a front part, and the front part grows from place 0.
The waits are 31, 12, 44, 7, 25, 38 and 20. The pivot is 20. The place store is where the next smaller value goes.
| Place | Value | Less than 20? | What happens | store after |
|---|---|---|---|---|
| 0 | 31 | no | stays | 0 |
| 1 | 12 | yes | swaps with the value at place 0 | 1 |
| 2 | 44 | no | stays | 1 |
| 3 | 7 | yes | swaps with the value at place 1 | 2 |
| 4 | 25 | no | stays | 2 |
| 5 | 38 | no | stays | 2 |
The last step swaps the pivot with the value at place 2. The list is 12, 7, 20, 31, 25, 38, 44. The 20 is in its final place, with smaller values before it and larger values after it.
Start with a correct version. It partitions around the last value and sorts each side the same way.
def quick_sort(values):
items = list(values)
def sort(lo, hi):
if lo >= hi:
return
pivot = items[hi]
store = lo
for j in range(lo, hi): # compare every value before the pivot
if items[j] < pivot:
items[store], items[j] = items[j], items[store]
store += 1
items[store], items[hi] = items[hi], items[store]
sort(lo, store - 1)
sort(store + 1, hi)
sort(0, len(items) - 1)
return itemsThis is correct. On a random list it makes about n log n comparisons. The team keeps it as the reference.
Now check the real size. The list arrives with the longest waits first. With the last value as pivot, every pivot is then the smallest or the largest value of its range.
The list has 100,000 requests in reverse order, and one comparison takes 1 microsecond.
Here is the count:
So the first attempt is as slow as selection sort, and it can crash.
Predict the cost
Q The list is in reverse order, and every pivot is the smallest or the largest value of its range. For 5,000 values, how many comparisons does this quick sort make?
Answer: C
Each partition compares every value of its range with the pivot, and the range shrinks by one each time. The sum is n × (n − 1) / 2, and a run on 5,000 sorted values counted 12,497,500.
The first attempt is correct, but one bad habit ruins it: it always takes the last value as the pivot. The fix is to choose the pivot well.
Think about what a good partition looks like. If the pivot lands near the middle, each side has about half of the values. The sort then has about log₂ n levels, like merge sort. If the pivot lands at the end, one side is empty, and the levels number n.
How often is a pivot good? Take 1,000 distinct values. A pivot is balanced when neither side holds more than three quarters of the values.
A pivot of rank r has r values below it and 999 − r above it. Ranks 249 to 750 are balanced, which is 502 of the 1,000 choices. About half of all pivots are good.
So a pivot picked at random is good about half the time. It does not matter in which order the list arrives, because the pick does not look at the order.
Race: Three pivot rules on an already sorted list. The operation counter loads in your browser.
The race sorts lists that are already in order. The last value as pivot makes 499,500 comparisons at 1,000 values, and a random pivot makes 10,652. A median of three, which takes the middle value of the first, middle and last, makes 7,987.
Lomuto scans from the left. Each value less than the pivot swaps into the store place, and the store place moves up.
The partition has two classic forms. Both work in place, and both put smaller values before larger ones. They differ in how they move.
Lomuto takes the last value as the pivot. One index j scans from the left, and a second index store marks where the next smaller value goes.
Each value less than the pivot swaps into place store. At the end, the pivot swaps into place store, which is its final place.
Hoare takes the first value as the pivot. Index i starts before the list and moves right past values less than the pivot. Index j starts after the list and moves left past values greater than it.
When both stop, they hold values on the wrong side, so they swap. The pass ends when i meets or passes j.
Every value up to j is at most the pivot, and every value after j is at least the pivot. Hoare does not put the pivot in its final place; it splits the list at j. So quick sort with Hoare's partition sorts lo to j and j + 1 to hi, and j stays in the left part.
Dry run: The same waits, split the Hoare way. The step-by-step player loads in your browser.
The trace shows Hoare's pass on the same seven waits. It makes 2 swaps, where Lomuto's pass made 3. On 10,000 seeded random waits, a full quick sort with Lomuto partitions makes 72,613 swaps that move a value. One with Hoare partitions makes 31,669.
Exercise · Predict the output: What does one Lomuto pass leave?. Seven waits, with the last one, 19, as the pivot. This is one Lomuto partition. What does it print?
items = [47, 12, 33, 8, 25, 40, 19]
pivot = items[-1]
store = 0
for j in range(len(items) - 1):
if items[j] < pivot:
items[store], items[j] = items[j], items[store]
store += 1
items[store], items[-1] = items[-1], items[store]
print(*items)The waits are [47, 12, 33, 8, 25, 40, 19]. Quick sort picks a random pivot, partitions, and sorts the smaller side first. The picks come from a seeded generator, so the run is the same every time. The player stops at five steps and asks you to predict.
Dry run: Predict each partition: seven waits. The step-by-step player loads in your browser.
Reading without the player? Cover the last three columns and predict them row by row.
| Partition | Range | Pivot | Pivot lands at | Values before it | Values after it |
|---|---|---|---|---|---|
| 1 | places 0 to 6 | 25 | place 3 | 3 | 3 |
| 2 | places 4 to 6 | 33 | place 4 | 0 | 2 |
| 3 | places 5 to 6 | 47 | place 6 | 1 | 0 |
| 4 | places 0 to 2 | 8 | place 0 | 0 | 2 |
| 5 | places 1 to 2 | 19 | place 2 | 1 | 0 |
The sort made 5 partitions for 7 values. Look at partition 1. The pivot 25 splits the list into three and three, which is the best split. A pivot that is the smallest or the largest value of its range, as 8 and 47 were, leaves the whole rest of the range as one side.
Predict the partition
Q A range of places 0 to 2 holds 12, 19 and 8, and the pivot is 8, the smallest value. Where does the pivot land?
Answer: C
A pivot ends at the place equal to the number of smaller values in its range. No value is smaller than 8, so it lands at place 0, and the other two values form one side.
A partition costs one comparison for each value of its range. With a good pivot, each level of the recursion costs n comparisons, and there are about log₂ n levels.
Here is the rule that keeps quick sort correct. Every line of the templates exists to protect it.
A partition puts the pivot in its final place, with smaller values before it and larger values after it, so each side can be sorted on its own.
During the scan, places lo to store - 1 hold values less than the pivot, and places store to j - 1 hold values that are not. When the scan ends, the swap puts the pivot between the two parts. Nothing before the pivot is larger, and nothing after it is smaller, so no value ever has to cross it again.
That is why the two sides are independent. Sorting the left side cannot disturb the right side. When both sides are sorted, the whole range is sorted, and no merge is needed.
Use it when you must sort in place, or split a list around a value, or find the k-th smallest value. Signal words: in place, split around a reference, the k-th smallest, many equal values, the list arrives sorted.
Start: a range of zero or one value is sorted. Otherwise pick a pivot, preferably at random.
Step: partition the range around the pivot. Sort the smaller side by recursion, and loop on the larger side.
Stop: when the range holds zero or one value. For quick select, stop when the target place falls on the pivot's place.
It does not keep equal values in their order, and it has a worst case of n² comparisons that a random pivot makes very unlikely.
Cost: O(n log n) expected time, O(n²) in the worst case, and O(log n) extra space for the recursion when the smaller side goes first.
def partition_last(values):
# [1] Work on a copy. The last value is the pivot, and store marks where the next smaller value goes.
items = list(values)
if not items:
return items
pivot = items[-1]
store = 0
# [2] Scan every value except the pivot.
for j in range(len(items) - 1):
# [3] A value less than the pivot swaps into the front part.
if items[j] < pivot:
items[store], items[j] = items[j], items[store]
store += 1
# [4] Put the pivot between the two parts, and return the list.
items[store], items[-1] = items[-1], items[store]
return itemspublic int[] partitionLast(int[] values) {
// [1] Work on a copy. The last value is the pivot, and store marks where the next smaller value goes.
int[] items = values.clone();
if (items.length == 0) {
return items;
}
int pivot = items[items.length - 1];
int store = 0;
// [2] Scan every value except the pivot.
for (int j = 0; j < items.length - 1; j++) {
// [3] A value less than the pivot swaps into the front part.
if (items[j] < pivot) {
int tmp = items[store];
items[store] = items[j];
items[j] = tmp;
store++;
}
}
// [4] Put the pivot between the two parts, and return the list.
int last = items.length - 1;
int tmp = items[store];
items[store] = items[last];
items[last] = tmp;
return items;
}vector<int> partitionLast(vector<int>& values) {
// [1] Work on a copy. The last value is the pivot, and store marks where the next smaller value goes.
vector<int> items = values;
if (items.empty()) {
return items;
}
int pivot = items.back();
int store = 0;
// [2] Scan every value except the pivot.
for (int j = 0; j < (int)items.size() - 1; j++) {
// [3] A value less than the pivot swaps into the front part.
if (items[j] < pivot) {
swap(items[store], items[j]);
store++;
}
}
// [4] Put the pivot between the two parts, and return the list.
swap(items[store], items.back());
return items;
}function partitionLast(values) {
// [1] Work on a copy. The last value is the pivot, and store marks where the next smaller value goes.
const items = [...values];
if (items.length === 0) {
return items;
}
const pivot = items[items.length - 1];
let store = 0;
// [2] Scan every value except the pivot.
for (let j = 0; j < items.length - 1; j++) {
// [3] A value less than the pivot swaps into the front part.
if (items[j] < pivot) {
[items[store], items[j]] = [items[j], items[store]];
store++;
}
}
// [4] Put the pivot between the two parts, and return the list.
[items[store], items[items.length - 1]] = [items[items.length - 1], items[store]];
return items;
}Exercise · Find the bug: The wait the scan never reads. This Lomuto partition leaves a smaller value on the wrong side of the pivot for some lists. Which line is wrong?
def partition_last(values):
items = list(values)
pivot = items[-1]
store = 0
for j in range(len(items) - 2):
if items[j] < pivot:
items[store], items[j] = items[j], items[store]
store += 1
items[store], items[-1] = items[-1], items[store]
return itemsdef partition_hoare(values):
# [1] Work on a copy. The first value is the pivot. The index i starts before the list and j after it.
items = list(values)
if not items:
return items
pivot = items[0]
i = -1
j = len(items)
while True:
# [2] Move i right past values less than the pivot, and j left past values greater than it.
i += 1
while items[i] < pivot:
i += 1
j -= 1
while items[j] > pivot:
j -= 1
# [3] When the two indexes meet or cross, the pass is over. Otherwise swap the two values and go on.
if i >= j:
break
items[i], items[j] = items[j], items[i]
# [4] Every value at or before j is at most the pivot, and every value after j is at least the pivot.
return itemspublic int[] partitionHoare(int[] values) {
// [1] Work on a copy. The first value is the pivot. The index i starts before the list and j after it.
int[] items = values.clone();
if (items.length == 0) {
return items;
}
int pivot = items[0];
int i = -1;
int j = items.length;
while (true) {
// [2] Move i right past values less than the pivot, and j left past values greater than it.
i++;
while (items[i] < pivot) {
i++;
}
j--;
while (items[j] > pivot) {
j--;
}
// [3] When the two indexes meet or cross, the pass is over. Otherwise swap the two values and go on.
if (i >= j) {
break;
}
int tmp = items[i];
items[i] = items[j];
items[j] = tmp;
}
// [4] Every value at or before j is at most the pivot, and every value after j is at least the pivot.
return items;
}vector<int> partitionHoare(vector<int>& values) {
// [1] Work on a copy. The first value is the pivot. The index i starts before the list and j after it.
vector<int> items = values;
if (items.empty()) {
return items;
}
int pivot = items[0];
int i = -1;
int j = (int)items.size();
while (true) {
// [2] Move i right past values less than the pivot, and j left past values greater than it.
i++;
while (items[i] < pivot) {
i++;
}
j--;
while (items[j] > pivot) {
j--;
}
// [3] When the two indexes meet or cross, the pass is over. Otherwise swap the two values and go on.
if (i >= j) {
break;
}
swap(items[i], items[j]);
}
// [4] Every value at or before j is at most the pivot, and every value after j is at least the pivot.
return items;
}function partitionHoare(values) {
// [1] Work on a copy. The first value is the pivot. The index i starts before the list and j after it.
const items = [...values];
if (items.length === 0) {
return items;
}
const pivot = items[0];
let i = -1;
let j = items.length;
while (true) {
// [2] Move i right past values less than the pivot, and j left past values greater than it.
i++;
while (items[i] < pivot) {
i++;
}
j--;
while (items[j] > pivot) {
j--;
}
// [3] When the two indexes meet or cross, the pass is over. Otherwise swap the two values and go on.
if (i >= j) {
break;
}
[items[i], items[j]] = [items[j], items[i]];
}
// [4] Every value at or before j is at most the pivot, and every value after j is at least the pivot.
return items;
}import random
def quick_sort(values):
items = list(values)
def sort(lo, hi):
# [1] Loop while the range holds two or more values.
while lo < hi:
# [2] Pick a random pivot and move it to the end of the range.
pick = random.randint(lo, hi)
items[pick], items[hi] = items[hi], items[pick]
# [3] Lomuto partition: values smaller than the pivot go to the front.
pivot = items[hi]
store = lo
for j in range(lo, hi):
if items[j] < pivot:
items[store], items[j] = items[j], items[store]
store += 1
items[store], items[hi] = items[hi], items[store]
# [4] Recurse into the smaller side, and loop on the larger side, so the depth stays below log2 n.
if store - lo < hi - store:
sort(lo, store - 1)
lo = store + 1
else:
sort(store + 1, hi)
hi = store - 1
sort(0, len(items) - 1)
return itemspublic int[] quickSort(int[] values) {
int[] items = values.clone();
sortRange(items, 0, items.length - 1);
return items;
}
private void sortRange(int[] items, int lo, int hi) {
// [1] Loop while the range holds two or more values.
while (lo < hi) {
// [2] Pick a random pivot and move it to the end of the range.
int pick = java.util.concurrent.ThreadLocalRandom.current().nextInt(lo, hi + 1);
int tmp = items[pick];
items[pick] = items[hi];
items[hi] = tmp;
// [3] Lomuto partition: values smaller than the pivot go to the front.
int pivot = items[hi];
int store = lo;
for (int j = lo; j < hi; j++) {
if (items[j] < pivot) {
int t = items[store];
items[store] = items[j];
items[j] = t;
store++;
}
}
int t = items[store];
items[store] = items[hi];
items[hi] = t;
// [4] Recurse into the smaller side, and loop on the larger side, so the depth stays below log2 n.
if (store - lo < hi - store) {
sortRange(items, lo, store - 1);
lo = store + 1;
} else {
sortRange(items, store + 1, hi);
hi = store - 1;
}
}
}static void sortRange(vector<int>& items, int lo, int hi) {
// [1] Loop while the range holds two or more values.
while (lo < hi) {
// [2] Pick a random pivot and move it to the end of the range.
int pick = lo + rand() % (hi - lo + 1);
swap(items[pick], items[hi]);
// [3] Lomuto partition: values smaller than the pivot go to the front.
int pivot = items[hi];
int store = lo;
for (int j = lo; j < hi; j++) {
if (items[j] < pivot) {
swap(items[store], items[j]);
store++;
}
}
swap(items[store], items[hi]);
// [4] Recurse into the smaller side, and loop on the larger side, so the depth stays below log2 n.
if (store - lo < hi - store) {
sortRange(items, lo, store - 1);
lo = store + 1;
} else {
sortRange(items, store + 1, hi);
hi = store - 1;
}
}
}
vector<int> quickSort(vector<int>& values) {
vector<int> items = values;
sortRange(items, 0, (int)items.size() - 1);
return items;
}function sortRange(items, lo, hi) {
// [1] Loop while the range holds two or more values.
while (lo < hi) {
// [2] Pick a random pivot and move it to the end of the range.
const pick = lo + Math.floor(Math.random() * (hi - lo + 1));
[items[pick], items[hi]] = [items[hi], items[pick]];
// [3] Lomuto partition: values smaller than the pivot go to the front.
const pivot = items[hi];
let store = lo;
for (let j = lo; j < hi; j++) {
if (items[j] < pivot) {
[items[store], items[j]] = [items[j], items[store]];
store++;
}
}
[items[store], items[hi]] = [items[hi], items[store]];
// [4] Recurse into the smaller side, and loop on the larger side, so the depth stays below log2 n.
if (store - lo < hi - store) {
sortRange(items, lo, store - 1);
lo = store + 1;
} else {
sortRange(items, store + 1, hi);
hi = store - 1;
}
}
}
function quickSort(values) {
const items = [...values];
sortRange(items, 0, items.length - 1);
return items;
}Rebuild the template: put its lines back in order. Loads in your browser.
Recurse into the smaller side and loop on the larger side, so each call handles at most half of its range.
The three templates share one question: where should the pivot go? You can answer it before you write code.
Then check the two ends: what do the templates do on an empty list, and on a list of equal values?
| Situation | Use | Why |
|---|---|---|
| The whole list, in place | Quick sort with a random pivot | n log n expected, little extra memory |
| One rank, such as the median | Quick select | Linear expected time |
| Many equal values | A three-way partition | Equal values are final after one pass |
| Equal records must keep their order | Merge sort | Quick sort is not stable |
The dispatcher wants the median of seven waits: 38, 12, 27, 9, 45, 3 and 20. The median is the value at place 3 of the sorted list. A full sort is not needed.
Partition around the last value with Template 1. The pivot is 20, and three values are smaller: 12, 9 and 3.
| Place | Value | Less than 20? | store after |
|---|---|---|---|
| 0 | 38 | no | 0 |
| 1 | 12 | yes | 1 |
| 2 | 27 | no | 1 |
| 3 | 9 | yes | 2 |
| 4 | 45 | no | 2 |
| 5 | 3 | yes | 3 |
The pivot lands at place 3, which is the target. So the median is 20, after one pass and 6 comparisons. The list is now 12, 9, 3, 20, 45, 27, 38.
Real data brings edge cases.
For values = [] or values = [5], the loop in the template does not run, since lo < hi is false. Both return the list unchanged.
For values = [7, 7, 7] repeated to 2,000 values, a Lomuto partition with a strict less-than test finds no smaller value, so each pivot splits n into 0 and n − 1. It makes 1,999,000 comparisons. Hoare's partition stops on equal values, so it swaps and splits close to the middle: for 1,000 equal values the first split was 500 and 500.
For values = [1, 2, 3, 4, 5] or [5, 4, 3, 2, 1], a random pivot is as good as on any other list. A sorted list of 5,000 values took 69,704 comparisons with a random pivot, against 12,497,500 with the last value.
For values = [3, 1, 3, 3, 1, 3] scaled up to 5,000 values from only 10 different numbers, a two-way partition makes about n² / 20 comparisons: a seeded run counted 1,276,269. A three-way partition, counting one comparison for each value it visits, counted 17,630. Each of its passes finishes all values equal to its pivot.
This version takes the last value as the pivot, as the first attempt did. A list that arrives sorted, or reversed, splits into n − 1 and 0 at every step.
Counterexample: a sorted list of 5,000 values makes 12,497,500 comparisons. A recursive version of this code on a sorted list of 1,000 values raises RecursionError in Python.
Pick the pivot at random, or take the median of three.
This version picks a random index but forgets to swap that value to the end of the range. The partition still reads the last value as its pivot, so the random pick has no effect.
Counterexample: on a sorted list of 5,000 values it makes 12,497,500 comparisons, exactly as the last value does.
Swap the picked value with the last place before the partition.
The last value as pivot on a sorted list splits n values into n minus one and none, and makes nearly n squared over two comparisons.
This version sorts places lo to store instead of lo to store - 1. The pivot is in its final place, and it must not be sorted again.
Counterexample: for [1, 2] the pivot lands at place 1, and the call sorts places 0 to 1 again. It never ends and raises RecursionError.
Sort lo to store - 1 and store + 1 to hi.
This version writes items[i] <= pivot in the loop that moves i. When no value to the right is larger, i runs off the end of the list.
Counterexample: for [2, 2] the index i passes place 1 and reads place 2, which raises IndexError. The same happens for [3, 1, 2].
Both loops stop on equal values. Use < for i and > for j.
Exercise · Break it: Find the three waits this median gets wrong. This function picks the middle value of three waits as a pivot. It compares the first with the second, and the second with the third. Find three waits where it returns the wrong value.
def median_of_three(a, b, c):
return max(min(a, b), min(b, c))A trip list is sorted by pickup minute, and trips with the same minute must stay in the order they were booked. Take the records (2, a), (2, b) and (1, c), compared by the number only.
The pivot (1, c) is last and no record is smaller, so the final swap exchanges it with (2, a). A Lomuto partition returns (1, c), (2, b), (2, a): the equal records changed order. Merge sort returns (1, c), (2, a), (2, b). Use a stable sort here.
Your team lead brings four product changes. Each one asks what the partition should look at.
The app needs the median wait of the latest window, not the whole order. Partition, and keep only the side that holds the target place. This is quick select, and the problem "Quick select on a stream window" practises it. It is also the idea behind LeetCode 215: Kth Largest Element in an Array.
Waits are rounded to a few buckets, so many are equal. A three-way partition puts smaller values first, equal values in the middle, and larger values last. The middle is final. The problem "Sort by a pivot without extra space" practises it, and LeetCode 75: Sort Colors is the three-value case.
The team asks how often a pivot is good. Sort once, and read each value's smaller and larger counts from its run of equal values. The problem "Avoid the worst pivot" counts the choices that leave at most three quarters on a side.
A real-time job cannot accept an n² worst case. The median-of-medians rule guarantees a good pivot, at the price of a larger constant. In practice, many libraries start with quick sort and switch to another method when the splits stay lopsided.
Explain it back: write the idea in your own words and get feedback.
In two or three sentences, explain to a teammate how quick sort works and why the pivot matters. Then say what a last-value pivot costs on a sorted list of 100,000 values. The AI tutor checks your answer against the invariant and the key points of this lesson.
Here is how you could explain it in an interview, now that you have counted it.
Quick sort partitions the list around a pivot, so smaller values come before it and larger values after it, and then it sorts each side the same way. The pivot ends in its final place. If it is the smallest or largest value every time, the cost is n squared: 4,999,950,000 comparisons for 100,000 values. I pick the pivot at random, recurse into the smaller side, and use a three-way partition when many values are equal.
Quick sort partitions the list around a pivot. Smaller values go before it, larger values go after it, and the pivot lands in its final place. Then I sort each side the same way, so no merge is needed.
It works in place. The cost depends on the pivot. A good pivot splits the list in a balanced way, so each of the log n levels costs n comparisons. A pivot that is always the smallest or largest costs n squared over 2, which is nearly 5 billion for 100,000 values.
So I pick the pivot at random, because about half of all pivots are good, whatever the order of the list. I recurse into the smaller side and loop on the larger, so the depth stays below log n. With many equal values I use a three-way partition. For one rank, such as the median, I follow only one side.
Checkpoint · The partition
Q1/3 What does one partition around a pivot do?
Answer: B
A partition splits the list around the pivot in one pass, in place. It does not sort each side, so quick sort repeats it on both sides.
Q2/3 In the Lomuto partition, what is the last step?
Answer: C
The scan leaves values less than the pivot at places before store. The final swap puts the pivot at place store, between the two parts.
Q3/3 The waits are 31, 12, 44, 7, 25, 38, 20, and the pivot is the last value, 20. At which place does the pivot land?
Answer: C
The pivot lands at the place equal to the number of smaller values. Only 12 and 7 are less than 20, so it lands at place 2.
Checkpoint · The pivot
Q1/3 Quick sort takes the last value as pivot, and the list is sorted. How many comparisons does it make for 1,000 values?
Answer: C
Each pivot is the largest value of its range, so each partition leaves n − 1 values and one empty side. The sum is n × (n − 1) / 2.
Q2/3 Why is a random pivot safe for any order of the list?
Answer: C
With 1,000 distinct values, ranks 249 to 750 are balanced: 502 of the 1,000 choices. A random pick does not look at the order, so it is good about half the time for every list.
Q3/3 Which statement about Hoare's partition is true?
Answer: B
Hoare takes the first value as pivot and moves i and j towards each other. A seeded full sort of 10,000 waits made 31,669 swaps with Hoare and 72,613 with Lomuto.
Checkpoint · Depth, equal values, selection
Q1/4 How do you keep the quick sort recursion below log₂ n calls deep?
Answer: C
Each recursive call then handles at most half of its range, so the depth is at most log₂ n, whatever the pivots are.
Q2/4 A two-way Lomuto partition sorts 2,000 equal values with a strict less-than test. How many comparisons does it make?
Answer: C
No value is less than the pivot, so every split is lopsided. The total is 2,000 × 1,999 / 2.
Q3/4 Quick select looks for the k-th smallest value. After a partition, the target place is smaller than the pivot's place. What does it do?
Answer: C
The pivot's place is final, so every value at a lower place is smaller. The target is among them, and the right side cannot hold it.
Q4/4 A trip list must be sorted by pickup minute, and trips with the same minute must keep their booking order. Which sort should you use?
Answer: C
A Lomuto partition can swap equal records: (2, a), (2, b), (1, c) became (1, c), (2, b), (2, a). Merge sort takes the left value on a tie, so it keeps the order.
Ten questions on this lesson. Pass with 80% or more to be sure the idea has landed before the next lesson.
| Step | Problem | Product line | Level | What it practises |
|---|---|---|---|---|
| 1 | One partition pass around a pivot | Rides | Easy | The Lomuto pass, in place |
| 2 | Sort by a pivot without extra space | Ads | Medium | A three-way partition and a shallow recursion |
| 3 | Quick select on a stream window | Pay | Medium | Following one side of a partition |
| 4 | Avoid the worst pivot | Search | Medium | Counting balanced pivot choices |
Review cards from this lesson.
Step through the idea on your own input, then build it in the lab. Runs in your browser. Step through it.
A few questions, then explain the idea back in your own words. Your tutor marks it. Quiz and explain back.