diff --git a/01_introduction_to_algorithms/ES6/02_recursive_binary_search.js b/01_introduction_to_algorithms/ES6/02_recursive_binary_search.js index 9fb9e96..d203777 100644 --- a/01_introduction_to_algorithms/ES6/02_recursive_binary_search.js +++ b/01_introduction_to_algorithms/ES6/02_recursive_binary_search.js @@ -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; }; /**