簡體   English   中英

JavaScript中的二進制搜索實現

[英]Binary search implementation in JavaScript

拜托,我碰到了實現二進制搜索的代碼,但是當我嘗試更改其中的某些內容時,卻得到了意想不到的結果。 這是代碼:

 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 有人可以把這些事情告訴我嗎?

嘗試這個 -

 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) ); 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM