标签:sea [] public int 算法 二分查找 二分 code private
public class Main {
private static int binary_search(int[] x, int key) {
int l = 0, r = x.length - 1;
while (l <= r) {
int m = (l + r) >>> 1;
if (x[m] == key) {
return m;
} else if (x[m] < key) {
++ l;
} else {
-- r;
}
}
return -1;
}
private static int lower_bound(int[] x, int key) {
int first = 0;
int len = x.length;
while (len > 0) {
int half = len >>> 1;
int m = first + half;
if (x[m] < key) {
// 右半区
first = m + 1;
len -= half + 1;
} else {
// 左半区
len = half;
}
}
return first;
}
private static int upper_bound(int[] x, int key) {
int first = 0;
int len = x.length;
while (len > 0) {
int half = len >>> 1;
int m = first + half;
if (x[m] <= key) {
// 右半区
first = m + 1;
len -= half + 1;
} else {
// 左半区
len = half;
}
}
return first;
}
public static void main(String[] args) {
}
}
标签:sea [] public int 算法 二分查找 二分 code private
原文地址:http://blog.51cto.com/tianyiya/2341719