码迷,mamicode.com
首页 > 编程语言 > 详细

Java经典编程题50道之三十

时间:2017-06-06 13:10:40      阅读:200      评论:0      收藏:0      [点我收藏+]

标签:example   print   数组   sys   stat   public   add   e30   ati   

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

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插入" + n + "后的数组为:");
        for (int r : b) {
            System.out.print(r + " ");
        }
    }
}

Java经典编程题50道之三十

标签:example   print   数组   sys   stat   public   add   e30   ati   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!