1.3二分查找

package array;


/**
 * 二分查找算法
 * @author 杨伦亮
 * 1:14:41 AM
 */
public class HighArray2 implements Find{
	private long[] a;
	private int nElement;
	
	/**构建函数*/
	public HighArray2(int max) {
		System.out.println("注意:必须是规则有序的队列!");
		a = new long[max];
		nElement = 0;
	}
	/*
	 * (non-Javadoc)
	 * @see array.Find#find(long)
	 */
	public Object find(long searchValue)throws Exception{
		int lowerPoint=0;
		int upperPoint=nElement-1;
		int curIn,time=0;
		try{
			while(true){
			curIn=(lowerPoint+upperPoint)/2;
			if(a[curIn]==searchValue) return curIn;
			else if(lowerPoint>upperPoint) return nElement;
			else {
				if(a[curIn]<searchValue){
					lowerPoint=curIn+1;
				}else{
					upperPoint=curIn-1;
				}
			}
			time++;	
		}

		}catch (Exception e) {
		}finally{
			System.out.println("run Times:"+time);
		}
		throw new Exception("can't find");
	}
	/**增加值*/
	public void insert(long value){
		a[nElement]=value;
		nElement++;
	}
	
	public int getSize(){
		return nElement;
	}
	
	/**删除指定值*/
	public boolean delete(long value){
		int j;
		for (j = 0; j < nElement; j++) {
			if(a[j]==value){
				break;
			}
		}
		if(j==nElement){
			return false;
		}else {
			for (int k = j; (k+1) < nElement; k++) {
				a[k]=a[k+1];
			}
			nElement--;
			return true;
		}
	}
	/**显示*/
	public void display(){
		for (int i = 0; i<nElement; i++) {
			System.out.print(a[i]+" ");
		}
		System.out.println();
	}
/**
  * @param args
  */
 public static void main(String[] args) throws Exception{
  // TODO Auto-generated method stub
  // TODO Auto-generated method stub
  int maxSize=100;
  HighArray2 array=new HighArray2(maxSize);
  
  for (int i = 0; i < maxSize; i++) {
   array.insert(i);
  }
  array.display();
  int searchValue=35;
  Object object=array.find(searchValue);
  System.out.println(searchValue+" Fount at \t"+object.toString());
  
 }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值