Skip to content

Commit 89189e5

Browse files
committed
Enhance IterativeBinarySearch with null safety and improved documentation
1 parent df28478 commit 89189e5

File tree

2 files changed

+10
-39
lines changed

2 files changed

+10
-39
lines changed

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

Lines changed: 0 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -131,43 +131,6 @@ else if (comp < 0) {
131131
return search(array, key, median + 1, right);
132132
}
133133
}
134-
135-
/**
136-
* Iterative implementation of binary search.
137-
* This version avoids recursion and uses constant space O(1).
138-
*
139-
* @param <T> The type of elements in the array (must be Comparable)
140-
* @param array The sorted array to search in
141-
* @param key The element to search for
142-
* @return The index of the key if found, -1 otherwise
143-
*/
144-
public <T extends Comparable<T>> int findIterative(T[] array, T key) {
145-
146-
// Handle edge cases
147-
if (array == null || array.length == 0 || key == null) {
148-
return -1;
149-
}
150-
151-
int left = 0;
152-
int right = array.length - 1;
153-
154-
while (left <= right) {
155-
156-
int median = (left + right) >>> 1;
157-
158-
int comp = key.compareTo(array[median]);
159-
160-
if (comp == 0) {
161-
return median;
162-
} else if (comp < 0) {
163-
right = median - 1;
164-
} else {
165-
left = median + 1;
166-
}
167-
}
168-
169-
return -1;
170-
}
171134
}
172135

173136

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

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -33,15 +33,22 @@ public final class IterativeBinarySearch implements SearchAlgorithm {
3333
*/
3434
@Override
3535
public <T extends Comparable<T>> int find(T[] array, T key) {
36-
if (array == null || array.length == 0) {
36+
37+
// Handle edge cases: null/empty array or null key
38+
// Prevents NullPointerException during comparison
39+
if (array == null || array.length == 0 || key == null) {
3740
return -1;
3841
}
3942

4043
int left = 0;
4144
int right = array.length - 1;
4245

4346
while (left <= right) {
47+
48+
// Use unsigned right shift to avoid overflow
49+
// Equivalent to (left + right) / 2 but safer for large indices
4450
int mid = (left + right) >>> 1;
51+
4552
int cmp = key.compareTo(array[mid]);
4653

4754
if (cmp == 0) {
@@ -53,6 +60,7 @@ public <T extends Comparable<T>> int find(T[] array, T key) {
5360
}
5461
}
5562

63+
// Element not found
5664
return -1;
5765
}
58-
}
66+
}

0 commit comments

Comments
 (0)