Skip to content

Commit df28478

Browse files
committed
Add iterative implementation of binary search
1 parent 9729e56 commit df28478

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

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

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -131,4 +131,43 @@ 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+
}
134171
}
172+
173+

0 commit comments

Comments
 (0)