二分搜索算法就是折半查找,是一种效率较高的查找方法。前提条件是要查找的数组是有序的。算法的实现还是相对简单的:
function binarySearch(arr,item){
var min = 0;
var max = arr.length-1;
var mid;
var ele;
while(max>=min){
mid = Math.floor((min+max)/2)
ele = arr[mid];
if(ele>item){
max = mid-1;
}
else if(ele<item){
min = mid + 1;
}
else{
return mid;
}
}
return -1;
}
binarySearch([2,5,7,9,12,34,65,78,98,231,542],5); //1