Skip to content

Commit 79cdb98

Browse files
authored
Add input validation and clarify sorted array requirement in Binary Search (#7216)
Added input validation and clarify sorted array rrequirement in Binary Search
1 parent 48f6322 commit 79cdb98

File tree

1 file changed

+6
-1
lines changed

1 file changed

+6
-1
lines changed

src/main/java/com/thealgorithms/searches/BinarySearch.java

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,9 @@
55
/**
66
* Binary search is one of the most popular algorithms The algorithm finds the
77
* position of a target value within a sorted array
8-
*
8+
* IMPORTANT
9+
* This algorithm works correctly only if the input array is sorted
10+
* in ascending order.
911
* <p>
1012
* Worst-case performance O(log n) Best-case performance O(1) Average
1113
* performance O(log n) Worst-case space complexity O(1)
@@ -25,6 +27,9 @@ class BinarySearch implements SearchAlgorithm {
2527
*/
2628
@Override
2729
public <T extends Comparable<T>> int find(T[] array, T key) {
30+
if (array == null || array.length == 0) {
31+
return -1;
32+
}
2833
return search(array, key, 0, array.length - 1);
2934
}
3035

0 commit comments

Comments
 (0)