-
Notifications
You must be signed in to change notification settings - Fork 0
/
Search.java
57 lines (52 loc) · 1.09 KB
/
Search.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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
class Search {
//return index
private static short NonSentinelSearch(int[] a, int k) {
int i = 1;
while (i <= a.length -1) {
if (a[i] == k) {
return (short)i;
}
i++;
}
return -1;
}
private static short SentinelSearch(int[] a, int k) {
int i = a.length -1;
while(i >= 0 && a[i] != k) {
i--;
}
return (short)i;
}
private static short BinarySearch(int[] a, int k) {
int i = -1;
int l=1;
int u=a.length-1;
boolean done = false;
int m;
while (l<=u && !done) {
m = (l+u)/2;
if (k > a[m]) {
l=m+1;
}
else if (k < a[m]) {
l=m-1;
}
else {
i=m;
done = true;
}
}
return (short)i;
}
public static void main(String[] args) {
int[] a1 = new int[] {1, 2, 5, 6, 13, 8, 26, 37};
int[] a2 = new int[] {1, 2, 5, 6, 8, 13, 26, 37};
short nss;
nss = NonSentinelSearch(a1, 37);
System.out.println(nss);
nss = SentinelSearch(a1, 5);
System.out.println(nss);
nss = BinarySearch(a2, 100);
System.out.println(nss);
}
}