一、递归方法
function binarySearch(arr,item,start,end){
var length = arr.length,
start = start || 0,
end = end || length -1,
mid = Math.floor((start+end)/2);
if (arr[mid] === item)
{
return mid;
}else if (arr[mid] > item)
{
return binarySearch(arr,item,start,mid-1);
}else{
return binarySearch(arr,item,mid+1,end);
}
return -1;
}
var array = [5,4,3,2,1].reverse();
console.log(binarySearch(array,2));
二、循环方法
function binarySearch(arr,item){
var length = arr.length,
start = 0,
end = length -1,
mid;
while ( start <= end )
{
mid = Math.floor((start+end)/2);
if (arr[mid] === item)
{
return mid;
}else if (ar