forked from mgechev/javascript-algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathquickselect.js
More file actions
48 lines (45 loc) · 1.04 KB
/
Copy pathquickselect.js
File metadata and controls
48 lines (45 loc) · 1.04 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
(function (exports) {
'use strict';
// O(n)
function quickselect(arr, n, lo, hi) {
function partition(arr, lo, hi, pivotIdx) {
function swap(arr, i, j) {
var temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
var pivot = arr[pivotIdx];
swap(arr, pivotIdx, hi);
for (var i = lo; i < hi; i += 1) {
if (arr[i] < pivot) {
swap(arr, i, lo);
lo += 1;
}
}
swap(arr, hi, lo);
return lo;
}
if (arr.length <= n) {
return NaN;
}
lo = lo || 0;
hi = hi || arr.length - 1;
if (lo === hi) {
return arr[lo];
}
while (hi >= lo) {
var pivotIdx =
partition(arr, lo, hi, lo + Math.floor(Math.random() * (hi - lo + 1)));
if (n === pivotIdx) {
return arr[pivotIdx];
}
if (n < pivotIdx) {
hi = pivotIdx - 1;
} else {
lo = pivotIdx + 1;
}
}
return NaN;
}
exports.quickselect = quickselect;
}(typeof exports === 'undefined' ? window : exports));