Skip to content

Commit 9fd7759

Browse files
committed
update binary search implementation
1 parent 66b558e commit 9fd7759

File tree

1 file changed

+15
-26
lines changed

1 file changed

+15
-26
lines changed

src/main/java/problems/impl/BinarySearcher.java

Lines changed: 15 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -10,36 +10,25 @@ public class BinarySearcher {
1010
* @return the index of the target value, if it exists. If the target value does not exist, a NoSuchElementException is thrown.
1111
*/
1212
public static int search(int[] values, int target) {
13-
return searchSubArray(values, 0, values.length - 1, target);
14-
}
15-
16-
private static int searchSubArray(int[] values, int leftIndex, int rightIndex, int target) {
17-
if (values.length == 0 || leftIndex < 0 || rightIndex < 0) {
13+
if (values.length == 0) {
1814
throw new NoSuchElementException(String.format("Unable to find target: {} in values", target));
1915
}
2016

21-
if (target == values[leftIndex]) {
22-
return leftIndex;
23-
}
24-
25-
if (target == values[rightIndex]) {
26-
return rightIndex;
17+
int leftIndex = 0;
18+
int rightIndex = values.length - 1;
19+
while (leftIndex < rightIndex) {
20+
int middleIndex = leftIndex + (rightIndex - leftIndex) / 2;
21+
int middleValue = values[middleIndex];
22+
23+
if (target < middleValue) {
24+
rightIndex = middleIndex;
25+
} else if (target > middleValue) {
26+
leftIndex = middleIndex + 1;
27+
} else {
28+
return middleIndex;
29+
}
2730
}
2831

29-
int middleIndex = Double.valueOf(Math.floor((rightIndex - leftIndex) / 2)).intValue();
30-
31-
int middleValue = values[middleIndex];
32-
33-
if (target < middleValue) {
34-
return searchSubArray(values, leftIndex + 1, middleIndex - 1, target);
35-
}
36-
37-
else if (target > middleValue) {
38-
return searchSubArray(values, middleIndex + 1, rightIndex - 1, target);
39-
}
40-
41-
else {
42-
return middleIndex;
43-
}
32+
return leftIndex;
4433
}
4534
}

0 commit comments

Comments
 (0)