有序数组的二分法查询、删除、插入java代码

来源:互联网 发布:万彩动画大师 知乎 编辑:程序博客网 时间:2024/05/18 00:11

使用有序数组的好处是查找的速度快了很多,假设一个N维数组,无需情况下查找平均为N/2次,而在有序情况下使用二分法,查询次数为log2(N)次。

//升序数组的插入、删除和查找操作public class OrdArray {    private long[] a;    private int nElems;    public OrdArray(int max){        a=new long[max];        nElems=0;    }    public int size(){        return nElems;    }    //二分法查询    public int find(long searchKey){        int lowBound=0;        int upperBound=nElems-1;        int curIn;        while(true){            curIn=(lowBound+upperBound)/2;            if(a[curIn]==searchKey){                return curIn;            }else if(lowBound>upperBound){                return nElems;            }else{                if(a[curIn]<searchKey){                    lowBound=curIn+1;                }else{                    upperBound=curIn-1;                }            }        }    }    //插入    public void insert(long 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 boolean delete(long value){        int j=find(value);        if(j==nElems){            return false;        }else{            for(int k=j;k<nElems;k++){                a[k]=a[k+1];            }            nElems--;            return true;        }    }    //打印    public void display(){        for(int i=0;i<nElems;i++){            System.out.println(a[i]+" ");        }    }}
0 0
原创粉丝点击