二分查找:待查找的是有序的.
1,3,4,5,6,7,8,12,15,16,19,22,23,25,27
如要查找25
拿中间的来比较,如在这里是12比较,那么前面一半就排除掉了.然后再这样.如果是奇数,取中间,如果是
偶数个,那么取随便取两个都可以.
public class BinarySearch{
public static int search(int[] i,int value){
//1.首先要找到要比较的下标值,肯定是最大的加上最小的/2
int low=0;
int high=i.length-1;
int mid=0;
//2.当low<=high时表明还没找到.
while(low<=high){
mid=(low+high)/2;
for(int j=0;j<i.length;j++){
System.out.print(i[j]);
if(j==mid){
System.out.print("#");
}
System.out.print(" ");
}
System.out.println();
if(value>i[mid]){
low=mid+1;
}
if(value<i[mid]){
high=mid-1;
}
if(value==i[mid]){//表明找到了
return i[mid];
}
}
return -1;
}
public static void main(String[] args){
int[] i=new int[]{1,2,3,4,5,6,9};
int result=search(i,3);
System.out.println(result);
}
}