用java实现的一些插入(顺序和乱序)和查找(顺序和二分)

代码1

/*乱序插入和顺序查找*/
class HighArray
{
    private long[] a;
    private int nElems;
    private int j;

    public HighArray(int Max)
    {
        a = new long[Max];
        nElems = 0;
    }

    public boolean find(long searchKey)
    {
        for(j=0;jif(a[j]==searchKey)
            break;
        if(j==nElems)
            return false;
        else
            return true;
    }

    public void insert(long value)
    {
        a[nElems]=value;
        nElems++;
    }

    public void display()
    {
        for(j=0;jout.print(a[j]+" ");
        System.out.println();
    }
}
public class test1
{
    public static void main(String[] args)
    {
        int maxSize=100;
        HighArray arr;
        arr = new HighArray(maxSize);

        arr.insert(77);
        arr.insert(99);
        arr.insert(44);
        arr.insert(55);
        arr.insert(22);
        arr.insert(88);
        arr.insert(11);
        arr.insert(0);
        arr.insert(66);
        arr.insert(33);

        arr.display();

        int searchKey=35;
        if(arr.find(searchKey))
            System.out.println("Find "+searchKey);
        else
            System.out.println("Can't Find "+searchKey);
    }
}

代码2

/*顺序插入和二分查找*/
class OrdArray
{
    private long[] a;
    private int nElems;

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

    public int size()
    {return nElems;}

    public void insert(long value)
    {
        int j;
        for(j=0;jif(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 j=0;jout.print(a[j]+" ");
        System.out.println();
    }

    public int find(long searchKey)
    {
        int lowerBound=0;
        int upperBound=nElems-1;
        int curIn;

        while(true)
        {
            curIn=(lowerBound+upperBound)/2;

            if(a[curIn]==searchKey)
                return curIn;
            else if(lowerBound>upperBound)
                return nElems;
            else{
                if(a[curIn]1;
                else
                    upperBound=curIn-1;
            }
        }
    }
}

public class OrderedApp
{
    public static void main(String[] args)
    {
        int maxSize=100;
        OrdArray arr;
        arr=new OrdArray(maxSize);

        arr.insert(77);
        arr.insert(99);
        arr.insert(44);
        arr.insert(55);
        arr.insert(22);
        arr.insert(88);
        arr.insert(11);
        arr.insert(0);
        arr.insert(66);
        arr.insert(33);

        arr.display();

        int searchKey=55;
        if(arr.find(searchKey)!=arr.size())
            System.out.println("Found "+searchKey);
        else
            System.out.println("Can't Find "+searchKey);
    }
}

你可能感兴趣的:(java)