二分法查找 --JS 实现

  var indexOfSorted = function f(arr,n){
  //assume : arr has been sorted  
 var low = 0; 
var high = arr.length - 1; 
var mid = (low + high) / 2; 

 while(high - low > 1){
 if(n == arr[low]){return low;}
if (n == arr[high]){return high;}
 if(n == arr[mid]){return mid;} 
if(n > arr[mid]){ low = mid; mid = (low + high) / 2; } 
if(n < arr[mid]){ high = mid; mid = (low + high) / 2; } 
 }  

return -1;  

 }  


var sortedArr = new Array(1,4,7,9,11,12,21,26,33); 

console.log(indexOfSorted(sortedArr,12)); 

二分法查找 --JS 实现,古老的榕树,5-wow.com

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。