Update 02_recursive_binary_search.js (#125)

This commit is contained in:
Evgeniy
2019-10-31 00:31:50 +03:00
committed by Aditya Bhargava
parent 03db2855d6
commit ee7dcd3b3d

View File

@@ -7,25 +7,20 @@
* @return {(number | null)} Number if the value is found or NULL otherwise
*/
const binarySearch = ( list, item, low = 0, high = list.length - 1 ) => {
let arrLength = list.length;
while ( low <= high ) {
let mid = Math.floor((low + high) / 2);
let guess = list[mid];
let mid = Math.floor((low + high) / 2);
let guess = list[mid];
if ( guess === item ) {
return mid;
} else if ( guess > item ) {
high = mid - 1;
list = list.slice( 0, mid );
return binarySearch( list, item, low, high );
} else {
low = mid + 1;
list = list.slice( low, arrLength );
return binarySearch( list, item, low, high );
}
if ( low > high ) return null;
if ( guess === item ) {
return mid;
} else if ( guess > item ) {
high = mid - 1;
return binarySearch( list, item, low, high );
} else {
low = mid + 1;
return binarySearch( list, item, low, high );
}
return null;
};
/**