/**
* 折半查找法,前提是已经排好序的数组才可查找
*/
public class BinarySearch {
int[] bArr;
public void setArr(int[] bArr){
this.bArr=bArr;
}
public static void main(String[] args) {
int arrLength=16;
int[] bArr=new int[arrLength];
System.out.println("数组:");
bArr=new int[]{72,31,13,94,85,27,64,71,19,55,49,40,8,70,17,13};
for(int i=0;i<arrLength;i++){
//bArr[i]=(int)(Math.random()*100);
System.out.print(bArr[i]+" ");
}
System.out.println();
System.out.println("排序:");
QuickSort qs=new QuickSort();
qs.setArr(bArr);
qs.quickSort(0, bArr.length-1);
for(int i=0;i<arrLength;i++){
System.out.print(bArr[i]+" ");
}
BinarySearch bs=new BinarySearch();
bs.setArr(bArr);
System.out.println();
System.out.println("查找:");
int val=bs.binarySearch(bArr.length-1, 0, 13);
System.out.println("查找:bArr["+val+"]="+13);
}
int binarySearch(int max,int min,int val){//有重复的取的是第一个出现的位置
int mid=(max+min)/2;
if(val==bArr[mid]){
return mid;
}
else if(val>bArr[mid]){
return binarySearch(max,mid,val);
}
else if(val<bArr[mid]){
return binarySearch(mid,min,val);
}
return -1;//查找失败
}
}