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.ts
function partition(arr: number[], low: number, high: number): number {
const pivot: number = arr[high];
let i: number = low - 1;
for (let j: number = 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: number[], low: number, high: number): void {
if (low < high) {
const pivotIndex: number = partition(arr, low, high);
quickSort(arr, low, pivotIndex - 1);
quickSort(arr, pivotIndex + 1, high);
}
}
const arr: number[] = [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
- TypeScript declares
partitionto acceptarr: number[],low: number, andhigh: number, returningnumber;quickSortuses the same typed bounds and returnsvoid, so the checked code mutates onenumber[]in place. partitionstoresconst pivot: number = arr[high], initializeslet i: number = low - 1, and scanslet j: number = lowwhilej < high.- The comparison
arr[j] <= pivotuses numericNumbervalues through TypeScript'snumbertype; equal values would be moved to the left side of the 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]], mutating array slots in place through source-level two-element RHS array expressions that engines may optimize. - The replay partitions around pivot
3:4and5stay right,1and2swap left, and the pivot lands at index2, yielding[1, 2, 3, 4, 5]before recursive calls on[1, 2]and[4, 5]. console.log(JSON.stringify(arr))prints[1,2,3,4,5]; visible heap allocation is the initial array and JSON output string, while recursive call frames and partition indices are execution state.
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.