Skip to content

Commit a34c308

Browse files
authored
fix: resolve formatting and build issues in IterativeBinarySearch
1 parent af1d9d1 commit a34c308

File tree

1 file changed

+29
-26
lines changed

1 file changed

+29
-26
lines changed

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

Lines changed: 29 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -3,50 +3,53 @@
33
import com.thealgorithms.devutils.searches.SearchAlgorithm;
44

55
/**
6-
* Binary search is one of the most popular algorithms This class represents
7-
* iterative version {@link BinarySearch} Iterative binary search is likely to
8-
* have lower constant factors because it doesn't involve the overhead of
9-
* manipulating the call stack. But in java the recursive version can be
10-
* optimized by the compiler to this version.
6+
* Binary search is one of the most popular algorithms.
7+
* This class represents the iterative version of {@link BinarySearch}.
118
*
12-
* <p>
13-
* Worst-case performance O(log n) Best-case performance O(1) Average
14-
* performance O(log n) Worst-case space complexity O(1)
9+
* <p>Iterative binary search avoids recursion overhead and uses constant space.
1510
*
16-
* @author Gabriele La Greca : https://github.com/thegabriele97
17-
* @author Podshivalov Nikita (https://github.com/nikitap492)
11+
* <p>Performance:
12+
* <ul>
13+
* <li>Best-case: O(1)</li>
14+
* <li>Average-case: O(log n)</li>
15+
* <li>Worst-case: O(log n)</li>
16+
* <li>Space complexity: O(1)</li>
17+
* </ul>
18+
*
19+
* @author Gabriele La Greca
20+
* @author Podshivalov Nikita
1821
* @see SearchAlgorithm
1922
* @see BinarySearch
2023
*/
2124
public final class IterativeBinarySearch implements SearchAlgorithm {
2225

2326
/**
24-
* This method implements an iterative version of binary search algorithm
27+
* Performs iterative binary search on a sorted array.
2528
*
26-
* @param array a sorted array
27-
* @param key the key to search in array
28-
* @return the index of key in the array or -1 if not found
29+
* @param array the sorted array
30+
* @param key the element to search
31+
* @param <T> type of elements (must be Comparable)
32+
* @return index of the key if found, otherwise -1
2933
*/
3034
@Override
3135
public <T extends Comparable<T>> int find(T[] array, T key) {
32-
int l;
33-
int r;
34-
int k;
35-
int cmp;
36+
if (array == null || array.length == 0) {
37+
return -1;
38+
}
3639

37-
l = 0;
38-
r = array.length - 1;
40+
int left = 0;
41+
int right = array.length - 1;
3942

40-
while (l <= r) {
41-
k = (l + r) >>> 1;
42-
cmp = key.compareTo(array[k]);
43+
while (left <= right) {
44+
int mid = (left + right) >>> 1;
45+
int cmp = key.compareTo(array[mid]);
4346

4447
if (cmp == 0) {
45-
return k;
48+
return mid;
4649
} else if (cmp < 0) {
47-
r = --k;
50+
right = mid - 1;
4851
} else {
49-
l = ++k;
52+
left = mid + 1;
5053
}
5154
}
5255

0 commit comments

Comments
 (0)