Java经典编程题50道之三十

有一个已经排好序的数组。现输入一个数,要求按原来的规律将它插入数组中。

public class Example30 {
    public static void main(String[] args) {
        int[] m = { 3, 5, 9, 12, 16, 20, 25, 33 };
        addElement(m, 17);
    }

    public static void addElement(int[] a, int n) {
        System.out.print("插入前的数组为:");
        for (int r : a) {
            System.out.print(r + " ");
        }
        int[] b = new int[a.length + 1];
        int i, j, k;
        for (i = 0; i < a.length; i++) {
            if (a[i] >= n) {
                for (j = a.length; j > i; j--)
                    b[j] = a[j - 1];
                b[i] = n;
                break;
            } else {
                b[a.length] = n;
            }
        }
        for (k = 0; k < i; k++)
            b[k] = a[k];
        System.out.print(" 插入" + n + "后的数组为:");
        for (int r : b) {
            System.out.print(r + " ");
        }
    }
}

原文地址:https://www.cnblogs.com/qubo520/p/6950817.html