diff --git a/src/main/java/com/thealgorithms/searches/BinarySearch.java b/src/main/java/com/thealgorithms/searches/BinarySearch.java index 7a5361b280ea..ca873fc6eafa 100644 --- a/src/main/java/com/thealgorithms/searches/BinarySearch.java +++ b/src/main/java/com/thealgorithms/searches/BinarySearch.java @@ -58,11 +58,18 @@ class BinarySearch implements SearchAlgorithm { */ @Override public > int find(T[] array, T key) { - // Handle edge case: empty array + // Handle edge case: null or empty array if (array == null || array.length == 0) { return -1; } + // Handle edge case: null key + // Searching for null in an array of Comparables is undefined behavior + // Return -1 to indicate not found rather than throwing NPE + if (key == null) { + return -1; + } + // Delegate to the core search implementation return search(array, key, 0, array.length - 1); }