-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathbinarySearch.java
More file actions
126 lines (120 loc) · 2.14 KB
/
binarySearch.java
File metadata and controls
126 lines (120 loc) · 2.14 KB
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
package binarysearch;
public class binarySearch {
//二分查找
public static int binNormalSearch(int p[], int key) {
if (p == null) {
return -1;
}
int start = 0;
int end = p.length - 1;
int mid;
while (start <= end) {
mid = (start + end) / 2;
if (p[mid] == key) {
return mid;
} else if (p[mid] > key) {
end = mid - 1;
} else {
start = mid + 1;
}
}
return -1;
}
//二分查找第一次出现的位置
public static int binFirstKSearch(int p[], int key) {
if (p == null) {
return -1;
}
int start = 0;
int end = p.length - 1;
int mid;
while (start < end) {
mid = (start + end) / 2;
if (p[mid] == key) {
end = mid;
} else if (p[mid] > key) {
end = mid - 1;
} else {
start = mid + 1;
}
}
if (p[start] == key) {
return start;
}
return -1;
}
//二分查找最后一次出现的位置
public static int binLastKSearch(int p[], int key) {
if (p == null) {
return -1;
}
int start = 0;
int end = p.length - 1;
int mid;
while (start < end - 1) {
mid = (start + end) / 2;
if (p[mid] == key) {
start = mid;
} else if (p[mid] > key) {
end = mid - 1;
} else {
start = mid + 1;
}
}
if (p[end] == key) {
return end;
}
if (p[start] == key) {
return start;
}
return -1;
}
//查找小于关键字的最大数字出现的位置
public static int binMaxLessKSearch(int p[], int key) {
if (p == null) {
return -1;
}
int start = 0;
int end = p.length - 1;
int mid;
while (start < end - 1) {
mid = (start + end) / 2;
if (p[mid] >= key) {
end = mid - 1;
} else {
start = mid;
}
}
if (p[end] < key) {
return p[end];
} else if (p[start] < key) {
return p[start];
} else {
return -1;
}
}
//查找大于关键字的最小数字出现的位置
public static int binMinMoreKSearch(int p[], int key) {
if (p == null) {
return -1;
}
int start = 0;
int end = p.length - 1;
int mid;
while (start < end - 1) {
mid = (start + end) / 2;
if (p[mid] <= key) {
start = mid + 1;
} else {
end = mid;
}
}
if (p[start] > key) {
return p[start];
} else if (p[end] > key) {
return p[end];
} else {
return -1;
}
}
}