简体   繁体   中英

Binary search implementation in JavaScript

Please, I came across this code that implements binary search but when I tried changing some things in it, I was getting results I didn't expect. Here's the code:

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

When I tried changing up some things in the code(which is shown in the commented portion of the code above) I get an unexpected result but I don't know WHY. And again what is the need of checking if (lo > hi) since hi should, as I think, always have a higher value than lo . Would hi ever be lower than lo ? Can someone please make these things clear to me?

Try this -

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM