forked from hitesh00025/Algorithms-In-Javascript
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinarySearch.js
More file actions
26 lines (20 loc) · 776 Bytes
/
Copy pathbinarySearch.js
File metadata and controls
26 lines (20 loc) · 776 Bytes
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
function binarySearch(items, value){
var startIndex = 0,
stopIndex = items.length - 1,
middle = Math.floor((stopIndex + startIndex)/2);
while(items[middle] != value && startIndex < stopIndex){
//adjust search area
if (value < items[middle]){
stopIndex = middle - 1;
} else if (value > items[middle]){
startIndex = middle + 1;
}
//recalculate middle
middle = Math.floor((stopIndex + startIndex)/2);
}
//make sure it's the right value
return (items[middle] != value) ? -1 : middle;
}
var items = ["a","b","c","d","e","f","g","h","i","j"];
console.log(binarySearch(items, "i")); //8
console.log(binarySearch(items, "b")); //1