Skip to content

Commit ee7dcd3

Browse files
hero1292egonSchiele
authored andcommitted
Update 02_recursive_binary_search.js (egonSchiele#125)
1 parent 03db285 commit ee7dcd3

File tree

1 file changed

+12
-17
lines changed

1 file changed

+12
-17
lines changed

01_introduction_to_algorithms/ES6/02_recursive_binary_search.js

Lines changed: 12 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -7,25 +7,20 @@
77
* @return {(number | null)} Number if the value is found or NULL otherwise
88
*/
99
const binarySearch = ( list, item, low = 0, high = list.length - 1 ) => {
10-
let arrLength = list.length;
11-
while ( low <= high ) {
12-
let mid = Math.floor((low + high) / 2);
13-
let guess = list[mid];
10+
let mid = Math.floor((low + high) / 2);
11+
let guess = list[mid];
1412

15-
if ( guess === item ) {
16-
return mid;
17-
} else if ( guess > item ) {
18-
high = mid - 1;
19-
list = list.slice( 0, mid );
20-
return binarySearch( list, item, low, high );
21-
} else {
22-
low = mid + 1;
23-
list = list.slice( low, arrLength );
24-
return binarySearch( list, item, low, high );
25-
}
26-
}
13+
if ( low > high ) return null;
2714

28-
return null;
15+
if ( guess === item ) {
16+
return mid;
17+
} else if ( guess > item ) {
18+
high = mid - 1;
19+
return binarySearch( list, item, low, high );
20+
} else {
21+
low = mid + 1;
22+
return binarySearch( list, item, low, high );
23+
}
2924
};
3025

3126
/**

0 commit comments

Comments
 (0)