二分法(二)
有序数组中找到>=num最左的位置
public class Code02_BSNearLeft {
public static int mostLeftNoLessNumIndex(int[] arr,int num){
if (arr == null || arr.length == 0){
return -1;
}
int L = 0;
int R = arr.length - 1;
int ans = -1;
while (L <= R){
int mid = ((R - L) >> 1) + L;
//System.out.println(mid);
if (arr[mid] >= num){
ans = mid;
R = mid -1;
} else {
L = mid + 1;
}
}
return ans;
}
public static int[] newArray(int maxLen,int maxValue){
int len = (int)(Math.random()*(maxLen+1));
int[] arr = new int[len];
for (int i = 0;i < len;i++){
arr[i] = (int)(Math.random()*(maxValue+1)) - (int)(Math.random()*maxValue);
}
return arr;
}
public static int test(int[] arr,int num){
if (arr == null || arr.length == 0){
return -1;
}
for (int i = 0;i < arr.length; i++){
if (arr[i] >= num) {
return i;
}
}
return -1;
}
public static void print(int[] arr){
for (int i = 0;i < arr.length;i++){
System.out.print(arr[i] + " ");
}
System.out.println();
}
//这是一个main方法,是程序的入口:
public static void main(String[] args) {
int testTime = 1000000;
int maxLen = 100;
int maxValue = 108;
for (int i = 0;i < testTime;i++){
int[] arr = newArray(maxLen,maxValue);
Arrays.sort(arr);
int num = (int) ((maxValue + 1) * Math.random()) - (int) (maxValue * Math.random());
if (mostLeftNoLessNumIndex(arr,num) != test(arr,num)){
System.out.println("出错了!");
System.out.println(num);
print(arr);
return;
}
}
System.out.println("正确!");
}
}