很少用JS来写算法, 需要注意的是JS是没有整形浮点型什么的 所以计算时要取整
var arr = [1,4,6,12,17,19,44,66,71]; function bisearch(arr,low, high, val){ var mid = parseInt((low + high)/2) ; if(low <= high){ if( arr[mid] == val){ return mid; }else{ if(arr[mid] < val){ return bisearch(arr,mid+1,high,val); } else{ return bisearch(arr,low,mid-1,val); } } }else{ return low; } } console.log(bisearch(arr,0,arr.length-1,44)); console.log(bisearch(arr,0,arr.length-1,55));
时间: 2024-10-13 12:01:47