Data Structures & Algorithms / Module 4: Searching and sorting
Topic 4.5
Quick sort
Partitioning around a pivot: fast and memory-light, as long as the pivot isn't bad.
Watch: one number is chosen as the marker. Smaller ones gather on its left, and the marker lands in its final place.
- moving now
- being checked
- passed / marked
- finished / the result
Like splitting a class by height
A teacher picks one pupil and says: "shorter than them, go left; taller, go right." That pupil is now standing in the right spot, even though both groups are still jumbled. Do the same inside each group, and the groups get smaller until everyone is in order. This splitting step is called a partition.
Code, for programmersQuick sort, pivot = last element
function quickSort(a, lo = 0, hi = a.length - 1) {
if (lo >= hi) return a;
const pivot = a[hi];
let i = lo; // a[lo..i-1] are smaller than pivot
for (let j = lo; j < hi; j++) {
if (a[j] < pivot) {
[a[i], a[j]] = [a[j], a[i]];
i++;
}
}
[a[i], a[hi]] = [a[hi], a[i]]; // pivot goes to its final spot
quickSort(a, lo, i - 1);
quickSort(a, i + 1, hi);
return a;
}When it is fast, when it is slow
If the pivot splits the list into roughly equal halves, it's the same story as merge sort: log n levels, n steps per level, n log n in total. In practice quick sort is often faster than merge sort because it works inside the same array and is cache-friendly.
But choose "already sorted" in the figure. The pivot is always the largest number, so every partition sets aside just one number. There are n levels instead of log n, and the total is about n²/2. Sorted data is very common in real life, so this is a real problem.
Quiz
After one partition, what is certainly true about the pivot?
Quick sort with the last element as pivot is given an already sorted list. What does it cost?
A common way to avoid quick sort's worst case?
0 of 3 answered.
Built on
Used in
No follow-up topics yet.