File tree Expand file tree Collapse file tree 1 file changed +12
-10
lines changed
Expand file tree Collapse file tree 1 file changed +12
-10
lines changed Original file line number Diff line number Diff line change 88 */
99
1010function binarySearchRecursive ( arr , x , low = 0 , high = arr . length - 1 ) {
11+ if ( ! Array . isArray ( arr ) || arr . length === 0 ) {
12+ return - 1
13+ }
14+
1115 const mid = Math . floor ( low + ( high - low ) / 2 )
1216
1317 if ( high >= low ) {
1418 if ( arr [ mid ] === x ) {
15- // item found => return its index
1619 return mid
1720 }
1821
1922 if ( x < arr [ mid ] ) {
20- // arr[mid] is an upper bound for x, so if x is in arr => low <= x < mid
2123 return binarySearchRecursive ( arr , x , low , mid - 1 )
2224 } else {
23- // arr[mid] is a lower bound for x, so if x is in arr => mid < x <= high
2425 return binarySearchRecursive ( arr , x , mid + 1 , high )
2526 }
26- } else {
27- // if low > high => we have searched the whole array without finding the item
28- return - 1
2927 }
28+
29+ return - 1
3030}
31+
3132function binarySearchIterative ( arr , x , low = 0 , high = arr . length - 1 ) {
33+ if ( ! Array . isArray ( arr ) || arr . length === 0 ) {
34+ return - 1
35+ }
36+
3237 while ( high >= low ) {
3338 const mid = Math . floor ( low + ( high - low ) / 2 )
3439
3540 if ( arr [ mid ] === x ) {
36- // item found => return its index
3741 return mid
3842 }
3943
4044 if ( x < arr [ mid ] ) {
41- // arr[mid] is an upper bound for x, so if x is in arr => low <= x < mid
4245 high = mid - 1
4346 } else {
44- // arr[mid] is a lower bound for x, so if x is in arr => mid < x <= high
4547 low = mid + 1
4648 }
4749 }
48- // if low > high => we have searched the whole array without finding the item
50+
4951 return - 1
5052}
5153
You can’t perform that action at this time.
0 commit comments