-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTestSearch.java
More file actions
35 lines (31 loc) · 760 Bytes
/
Copy pathTestSearch.java
File metadata and controls
35 lines (31 loc) · 760 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
public class TestSearch {
public static void main(String[] args) {
int a[] = { 1, 3, 6, 8, 9, 10, 12, 18, 20, 34 };
int i = 12;
//System.out.println(search(a, i));
System.out.println(binarySearch(a, i));
}
public static int search(int[] a, int num) {
for(int i=0; i<a.length; i++) {
if(a[i] == num) return i;
}
return -1;
}
public static int binarySearch(int[]a, int num) {
if (a.length==0) return -1;
int startPos = 0;
int endPos = a.length-1;
int m = (startPos + endPos) / 2;
while(startPos <= endPos){
if(num == a[m]) return m;
if(num > a[m]) {
startPos = m + 1;
}
if(num < a[m]) {
endPos = m -1;
}
m = (startPos + endPos) / 2;
}
return -1;
}
}