Skip to content
Closed
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
Add iterative implementation of binary search
  • Loading branch information
Mudita-Singh committed Apr 1, 2026
commit df28478e681d5d8e6a0a718c69610be70448be93
39 changes: 39 additions & 0 deletions src/main/java/com/thealgorithms/searches/BinarySearch.java
Original file line number Diff line number Diff line change
Expand Up @@ -131,4 +131,43 @@ else if (comp < 0) {
return search(array, key, median + 1, right);
}
}

/**
* Iterative implementation of binary search.
* This version avoids recursion and uses constant space O(1).
*
* @param <T> The type of elements in the array (must be Comparable)
* @param array The sorted array to search in
* @param key The element to search for
* @return The index of the key if found, -1 otherwise
*/
public <T extends Comparable<T>> int findIterative(T[] array, T key) {

// Handle edge cases
if (array == null || array.length == 0 || key == null) {
return -1;
}

int left = 0;
int right = array.length - 1;

while (left <= right) {

int median = (left + right) >>> 1;

int comp = key.compareTo(array[median]);

if (comp == 0) {
return median;
} else if (comp < 0) {
right = median - 1;
} else {
left = median + 1;
}
}

return -1;
}
}


Loading