-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathindex.js
More file actions
72 lines (59 loc) · 1.83 KB
/
Copy pathindex.js
File metadata and controls
72 lines (59 loc) · 1.83 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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
'use strict';
/**
* Calculates the index of the Array where item X should be placed, assuming the Array is sorted.
*
* @param {Array} array The array containing the items.
* @param {Number} x The item that needs to be added to the array.
* @param {Number} low Inital Index that is used to start searching, optional.
* @param {Number} high The maximum Index that is used to stop searching, optional.
* @returns {Number} the index where item X should be placed
*/
function bisection(array, x, low, high){
// The low and high bounds the inital slice of the array that needs to be searched
// this is optional
low = low || 0;
high = high || array.length;
var mid;
while (low < high) {
mid = (low + high) >> 1;
if (x < array[mid]) {
high = mid;
} else {
low = mid + 1;
}
}
return low;
}
/**
* A right bisection is default, so just reference the same function
*/
bisection.right = bisection;
/**
* Calculates the index of the Array where item X should be placed, assuming the Array is sorted.
* @param {Array} array The array containing the items.
* @param {number} x The item that needs to be added to the array.
* @param {number} low Inital Index that is used to start searching, optional.
* @param {number} high The maximum Index that is used to stop searching, optional.
* @return {number} the index where item X should be placed
*/
bisection.left = function left( array, x, low , high ){
// The low and high bounds the inital slice of the array that needs to be searched
// this is optional
low = low || 0;
high = high || array.length;
var mid;
while (low < high) {
mid = (low + high) >> 1;
if (x < array[mid]) {
low = mid + 1;
} else {
high = mid;
}
}
return low;
};
/**
* Library version
*/
bisection.version = '0.0.3';
module.exports = bisection;