-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
BinarySearch.java
47 lines (40 loc) · 1.41 KB
/
BinarySearch.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
/**
* Created by liuyubobobo on 11/21/17.
*/
public class BinarySearch {
private BinarySearch(){}
// 二分查找法, 实现lower_bound
// 即在一个有序数组arr中, 寻找大于等于target的元素的第一个索引
// 如果存在, 则返回相应的索引index
// 否则, 返回arr的元素个数 n
public static int lower_bound(Comparable[] arr, Comparable target){
if(arr == null)
throw new IllegalArgumentException("arr can not be null.");
int l = 0, r = arr.length;
while(l != r){
int mid = l + (r - l) / 2;
if(arr[mid].compareTo(target) < 0)
l = mid + 1;
else // nums[mid] >= target
r = mid;
}
return l;
}
// 二分查找法, 实现upper_bound
// 即在一个有序数组arr中, 寻找大于target的元素的第一个索引
// 如果存在, 则返回相应的索引index
// 否则, 返回arr的元素个数 n
public static int upper_bound(Comparable[] arr, Comparable target){
if(arr == null)
throw new IllegalArgumentException("arr can not be null.");
int l = 0, r = arr.length;
while(l != r){
int mid = l + (r - l) / 2;
if(arr[mid].compareTo(target) <= 0)
l = mid + 1;
else // nums[mid] > target
r = mid;
}
return l;
}
}