递归版
function BSearch( arr, x, low, high){
if( low > high ){
return -1;
}
var mid = parseInt((low + high) / 2);
if( x == arr[mid] ){
return mid;
}
else if( x < arr[mid] ){
return BSearch(arr, x, low, mid-1);
}
else{
return BSearch(arr, x, mid+1, high );
}
}
var arr = [1,3,4,5,17,18,31,44];
var f = BSearch( arr, 44, 0,arr.length-1 );
if( f=== -1 ){
console.log("查无此人");
}
else{
console.log("下标为"+f);
}
迭代版
function BSearch( arr, n, low, high ){
while( low <= high ){
var mid = parseInt( (low+high)/2 );
if( n < arr[mid] ){
high= mid-1;
}
else if( n>arr[mid] ){
low = mid+1;
}
else{
return mid;
}
}
return -1;
}
var arr = [1,3,4,5,17,18,31,44];
var f = BSearch( arr, 44, 0,arr.length-1 );
if( f=== -1 ){
console.log("查无此人");
}
else{
console.log("下标为"+f);
}