二分法(一)
有序数组中找到num
public class Code01_BSExist {
public static Boolean findNumIndex(int[] arr,int num){
if (arr == null || arr.length == 0){
return false;
}
int L = 0;
int R = arr.length - 1;
while (L <= R ){
int mid = ((R - L) >> 1) + L;
if (arr[mid] == num){
return true;
} else if(arr[mid] > num){
R = mid - 1;
} else{
L = mid + 1;
}
}
return false;
}
public static Boolean test(int[] arr,int num){
if (arr == null || arr.length == 0){
return false;
}
for (int i = 0;i < arr.length;i++){
if (arr[i] == num) {
return true;
}
}
return false;
}
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 void print(int[] arr){
//增强for循环
for(int a:arr){
System.out.print(a + " ");
}
System.out.println();
}
//这是一个main方法,是程序的入口:
public static void main(String[] args) {
int testTime = 1000000;
int maxLen = 100;
int maxValue = 1080;
int N = 10;
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 (findNumIndex(arr,num) ^ test(arr,num)){
System.out.println("错了!");
print(arr);
return;
}
}
System.out.println("正确!");
}
}