Skip to content

Instantly share code, notes, and snippets.

@carefree-ladka
Created June 11, 2024 14:16
Show Gist options
  • Save carefree-ladka/37e7ef267f570cc7a351c770de564b1f to your computer and use it in GitHub Desktop.
Save carefree-ladka/37e7ef267f570cc7a351c770de564b1f to your computer and use it in GitHub Desktop.
Quick Select Algorithm for finding Kth Max Element
function partition(a, lo, hi) {
/*
//Improve partition choice for the worst case
const randomIndex = Math.floor(Math.random() * (hi - lo + 1)) + lo;
swap(a, lo, randomIndex); // Move the random pivot to the start
*/
let i = lo;
let j = hi + 1;
let P = a[lo];
while (true) {
do {
i++;
} while (a[i] < P);
do {
j--;
} while (a[j] > P);
if (i >= j) break;
swap(a, i, j);
}
swap(a, lo, j);
return j;
}
const swap = (a, i, j) => ([a[i], a[j]] = [a[j], a[i]]);
function findKthLargest(nums, k) {
k = nums.length - k;
let lo = 0;
let hi = nums.length - 1;
while (lo <= hi) {
const j = partition(nums, lo, hi);
if (j === k) return nums[k];
else if (j < k) lo = j + 1;
else hi = j - 1;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment