Hey everyone, I’m working on a leaderboard feature and trying to grab the kth largest score without sorting the whole array, but my quickselect helper occasionally gives the wrong answer and that scares me more than the extra sort cost.
function kthLargest(nums, k) {
const target = nums.length - k;
function select(left, right) {
const pivot = nums[right];
let i = left;
for (let j = left; j < right; j++) {
if (nums[j] <= pivot) {
[nums[i], nums[j]] = [nums[j], nums[i]];
i++;
}
}
[nums[i], nums[right]] = [nums[right], nums[i]];
if (i === target) return nums[i];
if (i < target) return select(i, right);
return select(left, i - 1);
}
return select(0, nums.length - 1);
}
console.log(kthLargest([7, 2, 1, 8, 6, 3, 5, 4], 3));
What am I messing up in the partition recursion that makes this fail on some inputs?
Sora