编程导航算法通关村第三关|青铜挑战-不简单的数组增删改查

使用java实现数组的增删改查操作

package Array_;

public class Array_ {
    int size = 8;
    static int[] arr = {1, 2, 3, 4, 5, 6, 7, 8};

    public static void main(String[] args) {
        Array_ array = new Array_();
        array.trverse(arr);
        int search = array.search(arr, 8);
        System.out.println(search);

        int i = array.addBySize(arr, 6);
        System.out.println(i);
        array.trverse(arr);

        int delete = array.delete(arr, 3);
        array.trverse(arr);


    }

    //查找元素
    public int search(int[] arr, int num) {
        for (int i = 0; i < arr.length; i++) {
            if (arr[i] == num) {
                return i;
            }
        }
        return -1;
    }

    public int addBySize(int[] arr, int num) {
        if (size > arr.length) {
            return -1;
        }

        //找到要添加的位置
        int index = size;
        for (int i = 0; i < size; i++) {
            if (num < arr[i]) {
                index = i;
                break;
            }
        }
        //利用一个数组,实现扩容操作
        int[] newArr = new int[arr.length + 1];
        for (int i = 0; i < arr.length; i++) {
            newArr[i] = arr[i];
        }
        //元素后移添加元素
        for (int j = size; j > index; j--) {
            newArr[j] = newArr[j - 1];
        }
        newArr[index] = num;
        Array_.arr = newArr;
        size++;
        return index;
    }

    public int delete(int[] arr, int num) {
        int index = -1;
        for (int i = 0; i < arr.length; i++) {
            if (arr[i] == num) {
                index = i;
                break;
            }
        }
        if (index != -1) {
            //元素前移
            for (int i = index + 1; i < size; i++) {
                arr[i - 1] = arr[i];
            }
            size--;
        }
        return size;
    }


    public void trverse(int[] arrs) {
        for (int arr : arrs) {
            System.out.print(arr + " ");
        }
        System.out.println("size = " + size);
    }
}

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