二分法查找 --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 实现,布布扣,bubuko.com

二分法查找 --JS 实现

上一篇:Web服务器管理系列:12、开启关闭Ping命令


下一篇:Debian9 Stretch 升级到 Debian10 Buster 的方法 服务器在线升级DEBIAN10