码迷,mamicode.com
首页 > 其他好文 > 详细

实现2个排好序的子序列合并

时间:2016-09-22 06:31:17      阅读:166      评论:0      收藏:0      [点我收藏+]

标签:

数组a,b为已排序好的升序序列。

思路:1. 将a,b数组copy到一个新的数组c中(数组c的长度为a,b之和)

   2. 在c中以数组a为基准,当b中的数值小于a的时候,a中以后数值向后移1位,然后把当前b的值赋值过来。

具体实现:

public static int[] sort(int[] a, int[] b) {

        // 将a,b数组copy到数组c中
        int[] c = new int[a.length + b.length];
        System.arraycopy(a, 0, c, 0, a.length);
        System.arraycopy(b, 0, c, a.length, b.length);

        int i = 0, j = a.length, k;
        while (i < j) {
            if (j < c.length && c[i] > c[j]) {
                int tem = c[j];
                for (k = j; k > i; k--) {
                    c[k] = c[k - 1];
                }
                c[i] = tem;
                i++;
                j++;
            } else {
                i++;
            }
        }

        return c;
    }

 

实现2个排好序的子序列合并

标签:

原文地址:http://www.cnblogs.com/b-dong/p/5894768.html

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