function lomutoPartition(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 arr;
}
const arr = [8, 3, 7, 6, 2];
lomutoPartition(arr, 0, arr.length - 1);
console.log(arr);Lomuto partition picks last element as pivot (2). It moves all elements <= 2 to left. Only 2 is <= 2, so it swaps 2 with first element. Result: [2, 3, 7, 6, 8]
function hoarePartition(arr, low, high) {
let pivot = arr[low];
let i = low - 1;
let j = high + 1;
while (true) {
do {
i++;
} while (arr[i] < pivot);
do {
j--;
} while (arr[j] > pivot);
if (i >= j) return arr;
[arr[i], arr[j]] = [arr[j], arr[i]];
}
}
const arr = [5, 1, 4, 2, 8];
hoarePartition(arr, 0, arr.length - 1);
console.log(arr);Pivot is 5. Hoare moves i right until >=5 and j left until <=5, swapping elements. After swaps, array becomes [4, 1, 2, 5, 8].
Lomuto places pivot at its correct sorted position after partition. Hoare partition rearranges elements but pivot may not be at final position.
Initial i should be low - 1, not low. Starting at low causes pivot to be misplaced, off-by-one error.
Hoare partition ensures elements less than or equal to pivot are on one side, but pivot's final position is not fixed. So at least one element <= pivot is on left.
