二分法查找算法
import java.util.Arrays;public class Test3 {
public static int binarySearch(int[]a,int num) {
int low = 0;
int upper = a.length-1;
while (low<=upper) {
int mid = (low+upper)/2;
if (a[mid]<num) {
low = mid+1;
}else if(a[mid]>num){
upper = mid-1;
}else {
return mid;
}
}
return -1;
}
public static void main(String[] args) {
int []a ={1,4,6,32,7,3,7,2,87,2,87,5,9};
//顺序查找
/*for (int i = 0; i < a.length; i++) {
if (a[i] == 7) {
System.out.println(i);
}
}*/
Arrays.sort(a);//排序
for(int aa : a){
System.out.print(aa+" ");
}
System.out.println();
System.out.println(binarySearch(a, 7));
}
}