-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinarysearch.java
More file actions
30 lines (26 loc) · 783 Bytes
/
binarysearch.java
File metadata and controls
30 lines (26 loc) · 783 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
public class MyProgram
{
public static void main(String[] args)
{
//values have to be sorted first
int []arr = {2, 5, 10, 13, 23, 27, 41};
int goal = 41;
int low = 0;
int high = arr.length - 1;
for (int i = 0; low <= high; i++){
int half = low + (high - low) / 2;
if (goal > arr[half]) {
low = half + 1;
System.out.println(arr[half]);
}
else if (goal < arr[half]){
high = half - 1;
System.out.println(arr[half]);
}
else {
System.out.println("FOUND! " + arr[half] + " at index " + half);
return;
}
}
}
}