package test;
import java.util.Arrays;
public class N172 {
public static void main(String[] args) {
int[] a = { 1, 34, 4, 4, 5, 4, 6, 2345, 0 };
Arrays.sort(a);
System.out.println(Arrays.toString(a));
System.out.println(search(0, a.length - 1, 4, a));
System.out.println(search2(0, a.length - 1, 4, a));
}
/**
* 找到第一个大于 x 的数的下标
*
* @param l
* @param r
* @param x
* @param a
* @return
*/
static int search(int l, int r, int x, int[] a) {
while (l <= r) {
int mid = (l + r) / 2;
if (x < a[mid]) {
r = mid - 1;
} else {
l = mid + 1;
}
}
return l;
}
/**
* 找到第一个小于 x 的下标
*
* @param l
* @param r
* @param x
* @param a
* @return
*/
static int search2(int l, int r, int x, int[] a) {
while (l <= r) {
int mid = (l + r) / 2;
if (x <= a[mid]) {
r = mid - 1;
} else {
l = mid + 1;
}
}
return r;
}
}