Created
May 13, 2024 15:06
-
-
Save carefree-ladka/087a257a442c937272b1892c0fd45ae5 to your computer and use it in GitHub Desktop.
QUICK SELECT ALGORITHM
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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