Skip to content

Instantly share code, notes, and snippets.

@carefree-ladka
Created May 13, 2024 15:06
Show Gist options
  • Select an option

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

Select an option

Save carefree-ladka/087a257a442c937272b1892c0fd45ae5 to your computer and use it in GitHub Desktop.
QUICK SELECT ALGORITHM
const quickSelect = (nums, k, kthMax) => {
if (!nums.length) return;
const P = nums[Math.floor(Math.random() * nums.length)];
const left = [];
const mid = [];
const right = [];
nums.forEach(x => {
if (x === P) mid.push(x);
else if (kthMax ? x > P : x < P) left.push(x);
else right.push(x);
});
const L = left.length;
const M = mid.length;
if (k <= L) return quickSelect(left, k, kthMax);
else if (k > L + M) return quickSelect(right, k - L - M, kthMax);
return mid[0];
}
console.log(quickSelect([3, 2, 1, 5, 6, 4], 2, false)); // Output: 2 (2nd smallest)
console.log(quickSelect([3, 2, 3, 1, 2, 4, 5, 5, 6], 4, true)); // Output: 4 (4th largest)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment