File tree Expand file tree Collapse file tree 1 file changed +39
-0
lines changed
src/main/java/com/thealgorithms/searches Expand file tree Collapse file tree 1 file changed +39
-0
lines changed Original file line number Diff line number Diff 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+
You can’t perform that action at this time.
0 commit comments