算法:当数据量很大适宜采用该方法。采用二分法查找时,数据需是有序不重复的。 基本思想:假设数据是按升序排序的,对于给定值 x,从序列的中间位置开始比较,如果当前位置值等于 x,则查找成功;若 x 小于当前位置值,则在数列的前半段中查找;若 x 大于当前位置值则在数列的后半段中继续查找,直到找到为止。
假设有一个数组 {
20,21,22,23,24,25,26,27
public class TwoFindNum {
public static void main(String[] args) {
int []array=new int[]{20,21,22,23,24,25,26,27};
System.out.println(search(array, 21)); //如果查找的是数组中的值就返回元素对应的下标。否则返回-1.
System.out.println(search(array,30));
}
//二分查找
public static int search(int []array,int key){
int start=0;
int end=array.length-1; //长度从0开始,最后一位下标减1
while(start<end) {
int mid=(start+end)/2;
if (key<array[mid])
end=mid-1;
else if(key>array[mid]){
start=mid+1;
}else{
return mid;
}
}
return -1;
}
}
转载于:https://blog.51cto.com/xingyue2011/1950461