java学习之—递归实现二分查找法

/**
 * 递归实现二分查找法
 * Create by Administrator
 * 2018/6/21 0021
 * 上午 11:25
 **/
class OrdArray{
    private long[] a;
    private int nElems;

    public OrdArray(int max){
        this.a = new long[max];
        this.nElems = 0;
    }

    public int size(){
        return nElems;
    }

    public long find(long searchKey){
        return recFind(searchKey,0,nElems-1);
    }

    private long recFind(long searchKey, int lowerBound, int upperBound) {
        int curIn = (lowerBound+upperBound)/2;
        if(a[curIn] == searchKey){
            return a[curIn];
        }else if(lowerBound > upperBound){
            return 0;
        }else {
            if(a[curIn] < searchKey){
                return recFind(searchKey,curIn+1,upperBound);
            }else{
                return recFind(searchKey,lowerBound,curIn-1);
            }
        }
    }

    public void insert(long value){
        int j;
        for (j=0; j<nElems; j++){
            if(a[j] > value){
                break;
            }
        }
        for (int i = nElems; i > j; i--) {
            a[i] = a[i-1];
        }
        a[j] = value;
        nElems++;
    }

    public void  display(){
        for (int i = 0; i <nElems ; i++) {
            System.out.print(a[i] + " ");
        }
        System.out.println();
    }
}
public class BinarySearch {

    public static void main(String[] args) {
        int maxSize = 100;
        OrdArray array = new OrdArray(maxSize);
        array.insert(72);
        array.insert(90);
        array.insert(45);
        array.insert(126);
        array.insert(99);
        array.insert(144);
        array.insert(27);
        array.insert(135);
        array.insert(81);
        array.insert(108);
        array.insert(9);
        array.insert(117);
        array.insert(36);

        array.display();

        int searchKey = 27;
        long result = array.find(searchKey);
        System.out.println("返回结果:"+result+" (0表示未找到)");

    }

}

  

 

posted @ 2018-06-21 14:34  花儿为何那样红  阅读(664)  评论(0编辑  收藏  举报