二分查找实现插入操作的问题

sqq4290 2008-02-13 04:05:25
看外国的一本数据结构书籍遇到一个问题:
用二分查找算法实现有序无重复数组的插入操作,我用了一个inPos方法来找到插入的位置,用insert方法来进行插入,编译通过,运行的时候inPos方法出现死循环,求助解决的方法。
————————————————————————————————
//寻找插入位置的数组下表的方法inPos
public int inPos(long insertKey) // insertKey为要插入的数字
{
int lowerBound=0; //定义数组a的上界
int upperBound=nElems-1; /*定义数组a的下界,nElems为数组a中有效(不为0)元素总个数*/
int curIn; //查找光标停留在数组a[]中的当前位置

//开始查找
while(true)
{ curIn=(lowerBound+upperBound)/2; //二分查找
if(curIn==0)
{ if(a[0]>insertKey)
return 0;
}
else
{ if(a[curIn]>insertKey)
{
if(a[curIn-1]<=insertKey)
return curIn;
else
upperBound=curIn-1;
}
else
{
if(a[curIn+1]>insertKey)
return (curIn+1);
else
lowerBound=curIn+1;
}
}
}
}

//实现插入操作的方法insert
public void insert(long value) // 把要插入元素放入数组
{
int j=inPos(value);
for(int k=nElems; k>j; k--) // 移动较大的一个元素
a[k] = a[k-1];
a[j] = value; // 插入
nElems++; // 增加有效数组元素个数
}
...全文
209 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
老紫竹 2008-02-13
  • 打赏
  • 举报
回复
  public int inPos(long insertKey) // insertKey为要插入的数字
{
int lowerBound = 0; // 定义数组a的上界
int upperBound = nElems - 1; /* 定义数组a的下界,nElems为数组a中有效(不为0)元素总个数 */
int curIn; // 查找光标停留在数组a[]中的当前位置

// 开始查找
while (true) {
curIn = (lowerBound + upperBound) / 2; // 二分查找
if (curIn <= lowerBound) {
return lowerBound>0?lowerBound-1:0;
} else if (curIn >= upperBound) {
return upperBound;
} else {
if (a[curIn] > insertKey) {
if (a[curIn - 1] <= insertKey)
return curIn;
else
upperBound = curIn;
} else {
if (a[curIn + 1] > insertKey)
return (curIn + 1);
else
lowerBound = curIn;
}
}
}
}

62,623

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧