java版数据结构与算法—递归(二分法查找)

package com.zoujc.triangle;

/**
 * 递归:二分查找
 */
class OrdArray {
    private int[] a;
    private int nElems;
    public OrdArray(int max){
        a = new int[max];
        nElems = 0;
    }
    public int size(){
        return nElems;
    }
    public int recFind(int value,int low,int high){
        int curIn;
        curIn = (low + high)/2;
        if(a[curIn] == value){
            return curIn;
        }else if(low > high){
            return nElems;
        }else {
            if(a[curIn] < value){
                return recFind(value,curIn + 1,high);
            }else {
                return recFind(value,low,high - 1);
            }
        }
    }
    public void insert(int value){
        int j;
        for(j=0;j<nElems;j++){
            if(a[j]>value){
                break;
            }
        }
        for(int k =nElems;k>j;k--){
            a[k] = a[k-1];
        }
        a[j] = value;
        nElems ++;
    }
    public void display(){
        for(int i=0;i<nElems;i++){
            System.out.print(a[i] + " ");
        }
        System.out.println("");
    }
    public int find(int value){
        return recFind(value,0,nElems - 1);
    }
    public static void main(String[] args){
        OrdArray ordArray = new OrdArray(100);
        ordArray.insert(23);
        ordArray.insert(245);
        ordArray.insert(56);
        ordArray.insert(4);
        ordArray.insert(233);
        ordArray.insert(11);
        ordArray.insert(85);
        ordArray.insert(98);
        ordArray.insert(8);
        ordArray.insert(74);
        ordArray.display();
        int value = 74;
        if(ordArray.find(value) != ordArray.size()){
            System.out.println("found:" + value);
        }else {
            System.out.println("没有找到!");
        }
    }
}

在这里插入图片描述

你可能感兴趣的:(数据结构与算法)