|
11 | 11 | * |
12 | 12 | * [Reference](http://en.wikipedia.org/wiki/Quickselect) |
13 | 13 | */ |
14 | | -function quickSelectSearch(array, k) { |
| 14 | +function quickSelectSearch (array, k) { |
15 | 15 | if (!array || array.length <= k) { |
16 | | - throw new Error('Invalid arguments'); |
| 16 | + throw new Error('Invalid arguments') |
17 | 17 | } |
18 | 18 |
|
19 | | - let from = 0; |
20 | | - let to = array.length - 1; |
| 19 | + let from = 0 |
| 20 | + let to = array.length - 1 |
21 | 21 | while (from < to) { |
22 | | - let left = from; |
23 | | - let right = to; |
24 | | - const pivot = array[Math.ceil((left + right) * 0.5)]; |
| 22 | + let left = from |
| 23 | + let right = to |
| 24 | + const pivot = array[Math.ceil((left + right) * 0.5)] |
25 | 25 |
|
26 | 26 | while (left < right) { |
27 | 27 | if (array[left] >= pivot) { |
28 | | - const tmp = array[left]; |
29 | | - array[left] = array[right]; |
30 | | - array[right] = tmp; |
31 | | - --right; |
| 28 | + const tmp = array[left] |
| 29 | + array[left] = array[right] |
| 30 | + array[right] = tmp |
| 31 | + --right |
32 | 32 | } else { |
33 | | - ++left; |
| 33 | + ++left |
34 | 34 | } |
35 | 35 | } |
36 | 36 |
|
37 | 37 | if (array[left] > pivot) { |
38 | | - --left; |
| 38 | + --left |
39 | 39 | } |
40 | 40 |
|
41 | 41 | if (k <= left) { |
42 | | - to = left; |
| 42 | + to = left |
43 | 43 | } else { |
44 | | - from = left + 1; |
| 44 | + from = left + 1 |
45 | 45 | } |
46 | 46 | } |
47 | | - return array; |
| 47 | + return array |
48 | 48 | } |
49 | 49 |
|
50 | 50 | /* ---------------------------------- Test ---------------------------------- */ |
51 | 51 |
|
52 | 52 | const arr = [1121111, 21, 333, 41, 5, 66, 7777, 28, 19, 11110] |
53 | | -console.log(quickSelectSearch(arr, 5)); // [ 19, 21, 28, 41, 5, 66, 333, 11110, 1121111, 7777 ] |
54 | | -console.log(quickSelectSearch(arr, 2)); // [ 19, 5, 21, 41, 28, 333, 11110, 1121111, 7777, 66 ] |
55 | | -console.log(quickSelectSearch(arr, 7)); // [ 19, 5, 21, 41, 28, 66, 333, 7777, 11110, 1121111 ] |
| 53 | +console.log(quickSelectSearch(arr, 5)) // [ 19, 21, 28, 41, 5, 66, 333, 11110, 1121111, 7777 ] |
| 54 | +console.log(quickSelectSearch(arr, 2)) // [ 19, 5, 21, 41, 28, 333, 11110, 1121111, 7777, 66 ] |
| 55 | +console.log(quickSelectSearch(arr, 7)) // [ 19, 5, 21, 41, 28, 66, 333, 7777, 11110, 1121111 ] |
0 commit comments