MCPcopy
hub / github.com/mgechev/javascript-algorithms / quickselect

Function quickselect

src/searching/quickselect.js:24–64  ·  view source on GitHub ↗

* Returns the n-th smallest element of list within * lo..hi inclusive (i.e. lo <= n <= hi). * Time complexity: O(N). * * @example * * var quickselect = require('path-to-algorithms/src/searching/'+ * 'quickselect').quickselect; * var result = quickselect([5, 1, 2, 2, 0

(arr, n, lo, hi)

Source from the content-addressed store, hash-verified

22 * @return Returns n-th smallest element.
23 */
24 function quickselect(arr, n, lo, hi) {
25 function partition(arr, lo, hi, pivotIdx) {
26 function swap(arr, i, j) {
27 var temp = arr[i];
28 arr[i] = arr[j];
29 arr[j] = temp;
30 }
31 var pivot = arr[pivotIdx];
32 swap(arr, pivotIdx, hi);
33 for (var i = lo; i < hi; i += 1) {
34 if (arr[i] < pivot) {
35 swap(arr, i, lo);
36 lo += 1;
37 }
38 }
39 swap(arr, hi, lo);
40 return lo;
41 }
42
43 if (arr.length <= n) {
44 return undefined;
45 }
46 lo = lo || 0;
47 hi = hi || arr.length - 1;
48 if (lo === hi) {
49 return arr[lo];
50 }
51 while (hi >= lo) {
52 var pivotIdx =
53 partition(arr, lo, hi, lo + Math.floor(Math.random() * (hi - lo + 1)));
54 if (n === pivotIdx) {
55 return arr[pivotIdx];
56 }
57 if (n < pivotIdx) {
58 hi = pivotIdx - 1;
59 } else {
60 lo = pivotIdx + 1;
61 }
62 }
63 return undefined;
64 }
65 exports.quickselect = quickselect;
66
67})(typeof window === 'undefined' ? module.exports : window);

Callers 1

Calls 1

partitionFunction · 0.70

Tested by

no test coverage detected