-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinarySearch.java
More file actions
37 lines (29 loc) · 964 Bytes
/
BinarySearch.java
File metadata and controls
37 lines (29 loc) · 964 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
35
36
37
package BinarySearch;
import java.util.Arrays;
public class BinarySearch {
public static int find(int target, int ar[]) {
int lo = 0;
int hi = ar.length - 1;
// {1, 2, 3, 4, 5}
while (lo <= hi) {
int mid = (lo + hi) / 2; // mid is the position
int num = ar[mid]; // num is the actual # in the array at that position
System.out.println("trying: " + num);
if (num == target) {
return mid;
} else if (num < target) {
lo = mid + 1;
} else {
hi = mid - 1;
}
}
System.out.println("Did not find " + target);
return -1;
}
public static void main(String[] args) {
int ar[] = {1, 3, 5, 7, 38, 17, 19, 20, 32, 12};
Arrays.sort(ar);
int target = 1000;
System.out.println("Found " + target + " at position " + find(target, ar));
}
}