File tree Expand file tree Collapse file tree 1 file changed +7
-14
lines changed
lesson_07/conditionals/src Expand file tree Collapse file tree 1 file changed +7
-14
lines changed Original file line number Diff line number Diff line change @@ -85,31 +85,24 @@ export function binarySearch(
85
85
end : number ,
86
86
value : number ,
87
87
) : number {
88
- while ( start <= end ) {
89
- const mid = Math . floor ( ( start + end ) / 2 ) ;
90
- if ( values [ mid ] === value ) {
91
- return mid ;
92
- } else if ( values [ mid ] < value ) {
93
- start = mid + 1 ;
94
- } else {
95
- end = mid - 1 ;
96
- }
88
+ if ( start > end ) {
89
+ return - 1 ; // base case: not found
97
90
}
98
-
99
- const pivotIndex = Math . floor ( ( start + end ) / 2 ) ; // The index in the middle of the array.
91
+
92
+ const pivotIndex = Math . floor ( ( start + end ) / 2 ) ;
93
+
100
94
if ( values [ pivotIndex ] === value ) {
101
95
return pivotIndex ;
102
96
} else if ( values [ pivotIndex ] > value ) {
103
97
return binarySearch ( values , start , pivotIndex - 1 , value ) ;
104
98
} else {
105
99
return binarySearch ( values , pivotIndex + 1 , end , value ) ;
106
- return - 1 ;
107
100
}
101
+ }
108
102
109
103
// TODO(you): Finish implementing this algorithm
110
104
111
105
// If values[pivotIndex] is equal to value then return `pivotIndex`.
112
106
// Else if values[pivotIndex] is greater than the value, then
113
107
// call `binarySearch(values, start, pivotIndex - 1, value)` and return its value;
114
- // Else call `binarySearch(values, pivotIndex + 1, end, value)` and return its value.
115
- }
108
+ // Else call `binarySearch(values, pivotIndex + 1, end, value)` and return its value.
You can’t perform that action at this time.
0 commit comments