function partition(arr, left, right) {
const pivot = arr[right];
let i = left - 1;
for (let j = left; j < right; j++) {
if (arr[j] >= pivot) {
i++;
[arr[i], arr[j]] = [arr[j], arr[i]];
}
}
[arr[i + 1], arr[right]] =
[arr[right], arr[i + 1]];
return i + 1;
}
function quickSelect(arr, left, right, k) {
const pivotIndex = partition(arr, left, right);
if (pivotIndex === k)
return arr.slice(0, k);
else if (pivotIndex < k)
return quickSelect(arr, pivotIndex + 1, right, k);
else
return quickSelect(arr, left, pivotIndex - 1, k);
}
function topKElementsQuickSelect(arr, k) {
return quickSelect(arr, 0, arr.length - 1, k);
}
const arr = [3, 1, 4, 2, 3, 4, 4];
const k = 3;
console.log("Top", k, "elements:", topKElementsQuickSelect(arr, k));