-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
39 lines (36 loc) · 914 Bytes
/
index.js
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
function swap(data, i, j) {
if (i === j) {
return;
}
const tmp = data[j];
data[j] = data[i];
data[i] = tmp;
}
function partition(data, start, end) {
let i, j;
for (i = start + 1, j = start; i < end; i++) {
if (data[i] < data[start]) {
swap(data, i, ++j);
}
}
swap(data, start, j);
return j;
}
function findK(data, start, end, k) {
while (start < end) {
const pos = partition(data, start, end);
if (pos === k) {
return data[k];
}
if (pos > k) {
end = pos;
} else {
start = pos + 1;
}
}
}
// Calculate n-th percentile of 'data' using Nearest Rank Method
// http://en.wikipedia.org/wiki/Percentile#The_Nearest_Rank_method
export default function (data, n) {
return findK(data.slice(), 0, data.length, Math.ceil(data.length * n / 100) - 1);
}