js二分查找

为了适配业务,js写了个二分查找。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
function binarySearch(items,value){
var startIndex=0,
stopIndex=items.length-1,
middle=Math.floor((stopIndex+startIndex)/2);
while(items[middle]!=value && startIndex<stopIndex){
if(value<items[middle]){
stopIndex=middle-1;
}else if(value>items[middle]){
startIndex =middle+1;
}
middle=Math.floor((stopIndex+startIndex)/2)
}
return (items[middle]!=value) ? -1 : middle
}
console.log(binarySearch([1,2,3,4,5,6],6))