二分查找法

有序数组中的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++;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值