public int find(int[] a,int searchKey){
int nElems = a.length;
if(nElems<1)
return nElems;
int lowerBound = 0;
int upperBound = nElems-1;
int curIn;
while(true){
curIn = (lowerBound+upperBound)/2;
if(a[curIn]==searchKey)
return curIn;
else if(lowerBound>upperBound)
return nElems;
else{
if(a[curIn]<searchKey)
lowerBound = curIn+1;
else
upperBound = curIn-1;
}
}
}
在数据量较大时,较适合使用二分查找法。使用二分查找法的前提,数组必须是有序的,因此如果数组无序,要先对数组进行排序。
二分查找法的主要思想是:
1、获取数组长度nElems,进而得到中间位置curIn,a[curIn]便是数组中间位置的值。
2、拿要进行查找的值与中间位置值a[curIn]进行比较,如若相等,返回这个位置curIn,如果不等,进而将区间二分,获得一个新的范围,继续二分查找。
3、当上边界lowerBound大于下边界upperBound时,说明数组中没有这个要查找的值,返回数组长度。
本文首次发表依鹏csdn博客,转载注明出处http://blog.csdn.net/m0_37240709/article/details/78038296