function partition(arr, low, high) {
let 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;
}
let array = [8, 3, 7, 6, 2];
let pivotIndex = partition(array, 0, array.length - 1);
console.log(array);The partition function moves all elements smaller than the pivot (8) to the left. Here, 3 and 2 are less than 8 and get swapped to the front. The pivot 8 is placed after these smaller elements, resulting in [3, 2, 7, 6, 8].
function quickSort(arr, low = 0, high = arr.length - 1) { if (low < high) { let pi = partition(arr, low, high); quickSort(arr, low, pi - 1); quickSort(arr, pi + 1, high); } return arr; } function partition(arr, low, high) { let 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; } console.log(quickSort([4, 1, 5, 2]));
The quick sort algorithm recursively partitions and sorts the array. The final sorted array is [1, 2, 4, 5].
Choosing a pivot near the median splits the array into roughly equal parts, reducing recursion depth and improving performance.
function partition(arr, low, high) {
let pivot = arr[low];
let i = low + 1;
for (let j = low + 1; j <= high; j++) {
if (arr[j] < pivot) {
[arr[i], arr[j]] = [arr[j], arr[i]];
i++;
}
}
[arr[low], arr[i - 1]] = [arr[i - 1], arr[low]];
return i - 1;
}
let arr = [3, 6, 2];
let p = partition(arr, 0, arr.length - 1);
console.log(arr);The pivot swap uses arr[i], but i can be equal to high + 1, causing the pivot to swap with an element outside the partition range, leading to incorrect partitioning.
With perfect splits, quick sort forms a balanced binary recursion tree. For 7 elements, the recursion tree has 3 levels (ceil of log2(7)). Total calls = 2 * n - 1 = 13.
