Skip to content

Commit a52354a

Browse files
Add input validation for empty or invalid array in binary search
1 parent 22399de commit a52354a

File tree

1 file changed

+12
-10
lines changed

1 file changed

+12
-10
lines changed

Search/BinarySearch.js

Lines changed: 12 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -8,44 +8,46 @@
88
*/
99

1010
function 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+
3132
function 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

0 commit comments

Comments
 (0)