Partition around a pivot and avoid the quadratic worst case.
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.
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;
}def 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;
}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.
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.
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.
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.
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.
systemdesignmastery.dev/dsa/cheatsheets/quick-sort