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());
  
 }
}