一、二分法查找
1.思路
规定上下界;每次缩小一半的范围;如果所查找的值等于数组的中间值,则找到;如果中间值大,将下界变大;如果中间值较小,将上界变小;
2.java代码
public int find(long searchKey)
{
int lowerBound = 0;
int upperBound = nElems - 1;
int mid;
while (true)
{
mid = (lowerBound + upperBound) / 2;
if (a[mid] == searchKey)
return mid; // found it
else if (lowerBound > upperBound)
return nElems; // can't find it
else
// divide range
{
if (a[mid] < searchKey)
lowerBound = mid + 1; // it's in upper half
else
upperBound = mid - 1; // it's in lower half
} // end else divide range
二、利用二分法,对数组插值,要求数组从小到大排序
1.思路
A.数组个数为0时,直接插入值,并元素个数加一;
B.当个数不为0,则采用二分查找法
1.先查找合适位置;
a.当数组中间值(a[M])大于所插入的值(value)时;
1.M=0时;即将value放到数组的最左边;
2.value>a[M-1]时,即将value放到L和M之间;
3.H=M-1;
b.当数组中间值(a[M])小于所插入的值(value)时;
1.元素个数-1=M时;即将value放到数组的最右边;
2.value<a[M+1]时,即将value放到M和H之间;
3.L=M+1;
2.再插值
2.java代码
// put element into array 从小到大
public void BinaryInsert(long value)
{
//元素为0时,直接添加
if(nElems==0)
{
a[0]=value;
nElems++;
}
else
{
int low = 0;
int high = nElems-1;
int mid = 0;
while(true)
{
mid = (low+high)>>>1;
if(low>high) break; //越界
if(value == a[mid]) {break;} //找到
else if( a[mid]>value ) //value 小
{
if(mid == 0) break;
else if(a[mid-1]<value){break;}
else {high = mid-1;}
}
else //value 大
{
if(mid == nElems-1) { mid++; break; }
else if(value < a[mid+1]) { mid++; break;}
else {low = mid+1;}
}
}
//移位,留出适当位置,插值
for(int k = nElems; k>mid;k--)
{
a[k] = a[k-1];
}
a[mid]= value;
nElems++;
}
} // end BinaryInsert()
// -----------------------------------------------------------