|
3 | 3 | *
|
4 | 4 | * Notes:
|
5 | 5 | * -QuickSelect is related to QuickSort, thus has optimal best and average
|
6 |
| - * case (O(n)) but unlikely poor worst case (O(n^2)) |
| 6 | + * -case (O(n)) but unlikely poor worst case (O(n^2)) |
7 | 7 | * -This implementation uses randomly selected pivots for better performance
|
8 | 8 | *
|
9 | 9 | * @complexity: O(n) (on average )
|
10 | 10 | * @complexity: O(n^2) (worst case)
|
11 | 11 | * @flow
|
12 | 12 | */
|
13 | 13 |
|
14 |
| -function QuickSelect (items, kth) { |
| 14 | +function QuickSelect (items, kth) { // eslint-disable-line no-unused-vars |
| 15 | + if (kth < 1 || kth > items.length) { |
| 16 | + return 'Index Out of Bound' |
| 17 | + } |
| 18 | + |
15 | 19 | return RandomizedSelect(items, 0, items.length - 1, kth)
|
16 | 20 | }
|
17 | 21 |
|
@@ -62,5 +66,13 @@ function Swap (arr, x, y) {
|
62 | 66 | [arr[x], arr[y]] = [arr[y], arr[x]]
|
63 | 67 | }
|
64 | 68 |
|
65 |
| -// testing |
66 |
| -console.log(QuickSelect([1, 4, 2, -2, 4, 5])) |
| 69 | +// > QuickSelect([1, 4, 2, -2, 4, 5], 1) |
| 70 | +// -2 |
| 71 | +// > QuickSelect([1, 4, 2, -2, 4, 5], 5) |
| 72 | +// 4 |
| 73 | +// > QuickSelect([1, 4, 2, -2, 4, 5], 6) |
| 74 | +// 5 |
| 75 | +// > QuickSelect([1, 4, 2, -2, 4, 5], -1) |
| 76 | +// "Index Out of Bound" |
| 77 | +// > QuickSelect([1, 4, 2, -2, 4, 5], 7) |
| 78 | +// "Index Out of Bound" |
0 commit comments