二分法(三)
有序数组中找到<=num最右的位置
public class Code03_BSNearRight {
public static int nearestIndex(int[] arr,int num){
int N = arr.length;
if (arr == null || N == 0){
return -1;
}
int L = 0;
int R = N-1;
int ans = -1;
while (L <= R){
int mid = ((R - L) >> 1) + L;
if (arr[mid] > num){
R = mid - 1;
} else {
ans = mid;
L = mid + 1;
}
}
return ans;
}
public static int check(int[] arr,int num){
int N = arr.length;
if (arr == null || N == 0){
return -1;
}
for (int i = N-1;i >= 0;i--){
if (arr[i] <= num){
return i;
}
}
return -1;
}
public static int[] newArray(int maxLen,int maxValue){
int len = (int)(Math.random()*(maxLen+1));
int[] arr = new int[len];
if (len > 0){
for (int i = 0;i < len;i++){
arr[i] = (int)(Math.random()*(maxValue+1) - (int)(Math.random()*maxValue));
}
}
return arr;
}
public static void printArray(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 = 100;
for (int i = 0;i < testTime; i++){
int[] arr = newArray(maxLen, maxValue);
Arrays.sort(arr);
int num = (int)(Math.random()*(maxValue+1) - (int)(Math.random()*maxValue));
if(nearestIndex(arr,num) != check(arr,num)){
System.out.println("错了");
printArray(arr);
return;
}
}
System.out.println("正确");
}
}