数据结构____数组

数组在内存中一般是占用一个连续的内存空间进行储存(顺序存储),因此可以很好的实现逻辑上的顺序表

数组常用的操作:增,删,改,查

时间复杂度分别为(增-O(n)   查-O(1)   改-O(1)   删除-O(n))

所以数组一般都是用于查询为主的操作

增加(C)

 private int[] array;
    private int size;

    /*
     * 初始化数组
     * */
    //指定容量(带参构造函数)
    public init(int capacity) {
        this.array = new int[capacity];
        size = 0;
    }

    //默认容量(不带参构造函数)
    public init() {
        this.array = new int[20];
        size = 0;
    }

    /*
     * 插入元素
     * */
    public void insert(int element, int index) throws Exception {
        if (index < 0 || index > size) {
            throw new IndexOutOfBoundsException("数据插入位置异常!");
        }
        if (size >= array.length) {
            resize();
        }
        for (int i = size - 1; i > index; i--) {
            array[i + 1] = array[i];
        }
        array[index] = element;
        size++;
    }

    /*
     * 数组扩容
     * */
    public void resize() {
        int[] newArray = int[array.length * 2];
        System.arraycopy(array, 0, newArray, 0, array.length);
        array = newArray;
    }

读取(R)

    /*
    * 读取元素
    * */
    public int read(int index) throws Exception{
        if(index<0||index>size){
            throw new IndexOutOfBoundsException("读取超出数组范围");
        }
        return array[index];
    }

更新(U)

    /*
    * 更新元素
    * */
    public boolean update(int element,int index) throws Exception{
        if(index<0||index>size){
            throw new IndexOutOfBoundsException("读取超出数组范围");
        }
        array[index]=element;
        return true;
    }

删除(D)[根据索引删除]

    /*
    * 删除元素,根据索引删除
    * */
    public boolean delete(int index) throws Exception{
        if(index<0||index>size){
            throw new IndexOutOfBoundsException("超出数组范围");
        }
        for(int i =index;i<size-1;i++){
            array[i]=array[i+1];
        }
        array[size]=0;
        size--;
        return true;
    }

猜你喜欢

转载自www.cnblogs.com/KonataIzumi/p/12740735.html