-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMain.java
More file actions
34 lines (28 loc) · 853 Bytes
/
Main.java
File metadata and controls
34 lines (28 loc) · 853 Bytes
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
public class Main {
public static void main(String[] args) {
int[] myArray = new int[100];
for(int i = 0; i < 100; ++i) {
myArray[i] = 2 * i;
}
int index = binarySearch(myArray, 198);
if(index != -1){
System.out.println("Found "+ myArray[index] +" at position "+ index);
} else {
System.out.println("Value was not found");
}
}
static int binarySearch(int[] array, int target) {
int left = 0;
int right = array.length - 1;
while(left <= right) {
int mid = (left + right) / 2;
if(array[mid] == target)
return mid;
else if(array[mid] > target)
right = mid - 1;
else
left = mid + 1;
}
return -1;
}
}