Skip to content

Instantly share code, notes, and snippets.

@carefree-ladka
Last active August 12, 2024 13:26
Show Gist options
  • Select an option

  • Save carefree-ladka/8cf7c49aa85f9cd3fa213ec74acd1f4c to your computer and use it in GitHub Desktop.

Select an option

Save carefree-ladka/8cf7c49aa85f9cd3fa213ec74acd1f4c to your computer and use it in GitHub Desktop.
Quick Select Generic Solution for string & number
function partition(arr, lo, hi, compare) {
// Choose a random pivot and move it to the start
const randomIndex = Math.floor(Math.random() * (hi - lo + 1)) + lo;
swap(arr, lo, randomIndex);
const pivot = arr[lo];
let i = lo + 1; // Start just after the pivot
let j = hi;
while (i <= j) {
// Find the first element greater than or equal to the pivot
while (i <= hi && compare(arr[i], pivot) < 0) i++;
// Find the first element less than or equal to the pivot
while (j >= lo && compare(arr[j], pivot) > 0) j--;
if (i >= j) break;
swap(arr, i, j);
i++;
j--;
}
// Place the pivot in its correct position
swap(arr, lo, j);
return j; // Return the index of the pivot
}
const swap = (arr, i, j) => [arr[i], arr[j]] = [arr[j], arr[i]];
function quickSelect(arr, k, compare) {
let lo = 0;
let hi = arr.length - 1;
while (lo <= hi) {
const j = partition(arr, lo, hi, compare);
if (j === k) {
return arr[k];
} else if (j < k) {
lo = j + 1;
} else {
hi = j - 1;
}
}
return null; // In case k is out of bounds
}
const compare = (a, b) => BigInt(a) - BigInt(b);
function findKthLargest(arr, k) {
return quickSelect(arr, arr.length - k, compare);
}
function kthSmallestNumber(arr, k) {
return quickSelect(arr, k - 1, compare);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment