Update 02_recursive_binary_search.js (#125)
This commit is contained in:
@@ -7,25 +7,20 @@
|
|||||||
* @return {(number | null)} Number if the value is found or NULL otherwise
|
* @return {(number | null)} Number if the value is found or NULL otherwise
|
||||||
*/
|
*/
|
||||||
const binarySearch = ( list, item, low = 0, high = list.length - 1 ) => {
|
const binarySearch = ( list, item, low = 0, high = list.length - 1 ) => {
|
||||||
let arrLength = list.length;
|
let mid = Math.floor((low + high) / 2);
|
||||||
while ( low <= high ) {
|
let guess = list[mid];
|
||||||
let mid = Math.floor((low + high) / 2);
|
|
||||||
let guess = list[mid];
|
|
||||||
|
|
||||||
if ( guess === item ) {
|
if ( low > high ) return null;
|
||||||
return mid;
|
|
||||||
} else if ( guess > item ) {
|
if ( guess === item ) {
|
||||||
high = mid - 1;
|
return mid;
|
||||||
list = list.slice( 0, mid );
|
} else if ( guess > item ) {
|
||||||
return binarySearch( list, item, low, high );
|
high = mid - 1;
|
||||||
} else {
|
return binarySearch( list, item, low, high );
|
||||||
low = mid + 1;
|
} else {
|
||||||
list = list.slice( low, arrLength );
|
low = mid + 1;
|
||||||
return binarySearch( list, item, low, high );
|
return binarySearch( list, item, low, high );
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return null;
|
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
Reference in New Issue
Block a user