|
| 1 | +/** |
| 2 | + * QuickSelect is an algorithm to find the kth smallest number |
| 3 | + * |
| 4 | + * Notes: |
| 5 | + * -QuickSelect is related to QuickSort, thus has optimal best and average |
| 6 | + * case (O(n)) but unlikely poor worst case (O(n^2)) |
| 7 | + * -This implementation uses randomly selected pivots for better performance |
| 8 | + * |
| 9 | + * @complexity: O(n) (on average ) |
| 10 | + * @complexity: O(n^2) (worst case) |
| 11 | + * @flow |
| 12 | + */ |
| 13 | + |
| 14 | +function QuickSelect (items, kth) { |
| 15 | + return RandomizedSelect(items, 0, items.length - 1, kth) |
| 16 | +} |
| 17 | + |
| 18 | +function RandomizedSelect ( |
| 19 | + items, |
| 20 | + left, |
| 21 | + right, |
| 22 | + i |
| 23 | +) { |
| 24 | + if (left === right) return items[left] |
| 25 | + |
| 26 | + const pivotIndex = RandomizedPartition(items, left, right) |
| 27 | + const k = pivotIndex - left + 1 |
| 28 | + |
| 29 | + if (i === k) return items[pivotIndex] |
| 30 | + if (i < k) return RandomizedSelect(items, left, pivotIndex - 1, i) |
| 31 | + |
| 32 | + return RandomizedSelect(items, pivotIndex + 1, right, i - k) |
| 33 | +} |
| 34 | + |
| 35 | +function RandomizedPartition (items, left, right) { |
| 36 | + const rand = getRandomInt(left, right) |
| 37 | + Swap(items, rand, right) |
| 38 | + return Partition(items, left, right) |
| 39 | +} |
| 40 | + |
| 41 | +function Partition (items, left, right) { |
| 42 | + const x = items[right] |
| 43 | + let pivotIndex = left - 1 |
| 44 | + |
| 45 | + for (let j = left; j < right; j++) { |
| 46 | + if (items[j] <= x) { |
| 47 | + pivotIndex++ |
| 48 | + Swap(items, pivotIndex, j) |
| 49 | + } |
| 50 | + } |
| 51 | + |
| 52 | + Swap(items, pivotIndex + 1, right) |
| 53 | + |
| 54 | + return pivotIndex + 1 |
| 55 | +} |
| 56 | + |
| 57 | +function getRandomInt (min, max) { |
| 58 | + return Math.floor(Math.random() * (max - min + 1)) + min |
| 59 | +} |
| 60 | + |
| 61 | +function Swap (arr, x, y) { |
| 62 | + const temp = arr[x] |
| 63 | + arr[x] = arr[y] |
| 64 | + arr[y] = temp |
| 65 | +} |
| 66 | + |
| 67 | +// testing |
| 68 | +console.log(QuickSelect([1, 4, 2, -2, 4, 5])) |
0 commit comments