source: node_modules/victory-vendor/lib-vendor/d3-array/src/quickselect.js

Last change on this file was a762898, checked in by istevanoska <ilinastevanoska@…>, 5 months ago

Added visualizations

  • Property mode set to 100644
File size: 1.4 KB
Line 
1"use strict";
2
3Object.defineProperty(exports, "__esModule", {
4 value: true
5});
6exports.default = quickselect;
7var _sort = require("./sort.js");
8// Based on https://github.com/mourner/quickselect
9// ISC license, Copyright 2018 Vladimir Agafonkin.
10function quickselect(array, k, left = 0, right = array.length - 1, compare) {
11 compare = compare === undefined ? _sort.ascendingDefined : (0, _sort.compareDefined)(compare);
12 while (right > left) {
13 if (right - left > 600) {
14 const n = right - left + 1;
15 const m = k - left + 1;
16 const z = Math.log(n);
17 const s = 0.5 * Math.exp(2 * z / 3);
18 const sd = 0.5 * Math.sqrt(z * s * (n - s) / n) * (m - n / 2 < 0 ? -1 : 1);
19 const newLeft = Math.max(left, Math.floor(k - m * s / n + sd));
20 const newRight = Math.min(right, Math.floor(k + (n - m) * s / n + sd));
21 quickselect(array, k, newLeft, newRight, compare);
22 }
23 const t = array[k];
24 let i = left;
25 let j = right;
26 swap(array, left, k);
27 if (compare(array[right], t) > 0) swap(array, left, right);
28 while (i < j) {
29 swap(array, i, j), ++i, --j;
30 while (compare(array[i], t) < 0) ++i;
31 while (compare(array[j], t) > 0) --j;
32 }
33 if (compare(array[left], t) === 0) swap(array, left, j);else ++j, swap(array, j, right);
34 if (j <= k) left = j + 1;
35 if (k <= j) right = j - 1;
36 }
37 return array;
38}
39function swap(array, i, j) {
40 const t = array[i];
41 array[i] = array[j];
42 array[j] = t;
43}
Note: See TracBrowser for help on using the repository browser.