-
Notifications
You must be signed in to change notification settings - Fork 14
/
BinarySearch.java
34 lines (29 loc) · 935 Bytes
/
BinarySearch.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
package by.andd3dfx.search;
/**
* Implement binary search in a sorted array. Return element index or -1 if it doesn't exist
*
* @see <a href="https://youtu.be/RaxWD5yAQ9Q">Video solution</a>
*/
public class BinarySearch {
public static int perform(int[] array, int target) {
int left = 0;
int right = array.length - 1;
int steps = 0;
try {
while (left <= right) {
steps++;
int middle = Math.floorDiv(left + right, 2);
if (array[middle] < target) {
left = middle + 1;
} else if (array[middle] > target) {
right = middle - 1;
} else {
return middle;
}
}
return -1;
} finally {
System.out.println("Total steps count: " + steps);
}
}
}