有序数组中的find()方法
public int find(long serchKey)
{
int lowerBound = 0;
int upperBound =nElems-1;
while(true)
{
curIn= (lowerBound+upperBound)/2;
if(a[curIn==serchKey)
return curIn; //found it
else if (lowerBound>upperBound)
return nElems; //can't find it
else //divide range
{
if(a[curIn)<serchKey)
lowerBound=curIn+1;
else
upperBound=curIn-1;
}
}
}
有序数组的插入方法可使用的二分查找法
public int find(long searchKey)
{
//如果数组为空,直接插入,故插入位置为下标0
if(nElems == 0)
{
return 0;
}
//起始下标
int lowerBound = 0;
//结尾下标
int upperBound = nElems - 1;
//当前下标
int curIn;
while(true)
{
curIn = (lowerBound + upperBound) / 2;
if(a[curIn] > searchKey)
{
upperBound = curIn - 1;
if(lowerBound > upperBound)
{
return curIn;
}
}
else if(a[curIn] < searchKey)
{
lowerBound = curIn + 1;
if(lowerBound > upperBound)
{
return lowerBound;
}
}
}
}
然后是插入
public vod insert(long value)
{
int j=find(value);
for(int k=nElems;k>j;k--) //move bigger ones up
a[k]=a[k-1];
a[j]=value;
nElems++;
}