JavaScript中的二进制搜索实现

时间:2015-11-09 19:36:33

标签: javascript algorithm recursion

拜托,我遇到了实现二进制搜索的代码,但是当我尝试更改其中的一些内容时,我得到的结果是我没想到的。这是代码:

 function binary_search(list, lo, hi, key){
 var mid;

if (lo > hi)
{
    console.log("Key not found\n");
    return;
}
mid = Math.floor((lo + hi) / 2);
if (list[mid] == key)
{
    console.log("Key found\n");
    //return mid;  Expected this to return the index where the key was found 
   //but it returns undefined...
}
else if (list[mid] > key)
{
    binary_search(list, lo, mid - 1, key);
}
else if (list[mid] < key)
{
    binary_search(list, mid + 1, hi, key);
}
}

binary_search([1,3,5,6,7,9],0,5,1)// logs 'Key found' to the console(working correctly);

当我尝试更改代码中的某些内容(显示在上面代码的注释部分中)时,我得到了意想不到的结果,但我不知道为什么。再次检查if (lo > hi)的需要是什么,因为我认为hi应始终具有比lo更高的值。 hi是否会低于lo?有人可以把这些事情告诉我吗?

1 个答案:

答案 0 :(得分:0)

试试这个 -

function binarySearch(arr, num, l, r){
	if( arr instanceof Array ){
  	
    l = isNaN(l) ? 0 : l;
    r = isNaN(r) ? arr.length - 1: r;
    let mid = l + 1 + Math.round((r - l)/2 - 1);    
    console.log(l, r, mid, arr[mid]);
    
    if( num == arr[mid] ){ 
    	console.log("found"); 
      return mid; 
    }
    
    if( typeof arr[mid] == "undefined" || l == r ){
    	console.log("not found"); return -1;
    }
    
    if( num < arr[mid] ){  
    	console.log("take left"); 
      return binarySearch(arr, num, l, r - mid);
    }
    
    console.log("take right");
    return binarySearch(arr, num, mid, r);
    
  }
}

console.log( binarySearch([0, 0, 1 ,1, 2, 3, 5, 6, 11], 2) );