Sorting
Quick Sort (Lomuto)
Choose the last item as a pivot, partition smaller values to its left, then recurse on the two sides.
Algorithm
Basic Implementation
basic.js
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;
}
function quickSort(arr, low, high) {
if (low < high) {
const pivotIndex = partition(arr, low, high);
quickSort(arr, low, pivotIndex - 1);
quickSort(arr, pivotIndex + 1, high);
}
}
const arr = [4, 1, 5, 2, 3];
quickSort(arr, 0, arr.length - 1);
console.log(JSON.stringify(arr));
Complexity
- Time: O(n^2) worst, O(n log n) average
- Space: O(log n) average call stack
- Stable: no
Implementation notes
- JavaScript stores the sortable data in a
constArrayofNumbervalues.quickSortmutates that same array in place over inclusivelowandhighbounds, and recursion stops whenlow < highis false. partitionchoosesarr[high]as the pivot, initializeslet i = low - 1, and scansjwhilej < high. Thearr[j] <= pivottest uses numericNumbercomparison and sends values equal to the pivot to the left partition.- Swaps use destructuring assignment,
[arr[i], arr[j]] = [arr[j], arr[i]]and then[arr[i + 1], arr[high]] = [arr[high], arr[i + 1]]. Those writes mutate array slots in place; the right-hand destructuring arrays are short-lived runtime allocations. - The replay shows the first partition around pivot
3:4and5stay on the right,1and2swap left, and the pivot lands at index2, producing[1, 2, 3, 4, 5]before the summarized recursive calls on[1, 2]and[4, 5]. console.log(JSON.stringify(arr))prints the compact sorted output[1,2,3,4,5]. Aside from recursion stack frames, destructuring temporaries, and the output string, no replacement array is allocated.
pivot
The final element is moved to the boundary between smaller and larger values.
partition
One scan rearranges the current range before the recursive calls.