function partition(arr, left, right, pivotIndex) {
const pivotValue = arr[pivotIndex];
let storeIndex = left;
// Move pivot to the end
[arr[pivotIndex], arr[right]] =
[arr[right], arr[pivotIndex]];
// Partition the array
for (let i = left; i < right; i++) {
if (arr[i] < pivotValue) {
[arr[i], arr[storeIndex]] =
[arr[storeIndex], arr[i]];
storeIndex++;
}
}
// Move pivot to its final place
[arr[right], arr[storeIndex]] =
[arr[storeIndex], arr[right]];
return storeIndex;
}
function quickSelect(arr, left, right, k) {
while (left <= right) {
const pivotIndex = Math.floor(Math.random() *
(right - left + 1)) + left;
const partitionIndex =
partition(arr, left, right, pivotIndex);
if (partitionIndex === k) {
return arr[partitionIndex];
} else if (partitionIndex < k) {
left = partitionIndex + 1;
} else {
right = partitionIndex - 1;
}
}
}
function kthSmallestAfterRemoval(arr, k, MAX) {
const remainingNumbers = [];
let num = 1;
while (remainingNumbers.length < k) {
if (!arr.includes(num)) {
remainingNumbers.push(num);
}
num++;
}
return quickSelect(remainingNumbers, 0,
remainingNumbers.length - 1, k - 1);
}
const arr = [3, 5];
const k = 2;
const MAX = 10;
console.log("K-th smallest element after removal:",
kthSmallestAfterRemoval(arr, k, MAX));