-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathbinarySearch.js
37 lines (34 loc) · 934 Bytes
/
binarySearch.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
/**
* Performs a binary search on the provided sorted list and returns the index of the item if found. If it can't be found it'll return -1.
*
* @param {*[]} list Items to search through.
* @param {*} item The item to look for.
* @return {Number} The index of the item if found, -1 if not.
*/
function binarySearch(list, item) {
var min = 0;
var max = list.length - 1;
var guess;
var bitwise = (max <= 2147483647) ? true : false;
if (bitwise) {
while (min <= max) {
guess = (min + max) >> 1;
if (list[guess] === item) { return guess; }
else {
if (list[guess] < item) { min = guess + 1; }
else { max = guess - 1; }
}
}
} else {
while (min <= max) {
guess = Math.floor((min + max) / 2);
if (list[guess] === item) { return guess; }
else {
if (list[guess] < item) { min = guess + 1; }
else { max = guess - 1; }
}
}
}
return -1;
}
module.exports = binarySearch;