Every time you call .sort() in JavaScript,
Python, or Java — Quick Sort is running
under the hood.
Not Bubble Sort. Not Merge Sort. Quick Sort.
Why Quick Sort?
It combines two things perfectly:
- O(n log n) average performance
- In-place sorting — no extra memory needed
Merge Sort also achieves O(n log n) but
requires O(n) extra space. Quick Sort only
needs O(log n) stack space for recursion.
The Core Idea — The Pivot
\`javascript
function partition(arr, low, high) {
const pivot = arr[high];
let i = low - 1;
for (let j = low; j < high; j++) {
if (arr[j] <= pivot) {
i++;
[arr[i], arr[j]] = [arr[j], arr[i]];
}
}
[arr[i + 1], arr[high]] = [arr[high], arr[i + 1]];
return i + 1;
}
`\
Pick a pivot. Everything smaller goes left.
Everything larger goes right.
The pivot is now in its permanent position.
The One Weakness
Worst case is O(n²) — when pivot is always
the smallest or largest element.
Modern implementations use randomized pivot
selection to avoid this trap.
Watch It
What's Next
Linked Lists — a completely different
approach to storing data in memory.
Subscribe to AlgoCanvas:
👉 youtube.com/@AlgoCanvas
Top comments (0)