合并多个有序数组

public class JoinArray {
    public static void main(String[] args) {

        int[] a1 = {1, 3, 5, 7, 13};
        int[] a2 = {2, 4, 6, 12, 14};

        System.out.println(Arrays.toString(sort(a1, a2)));
    }
    public static int[] sort(int[] a, int[] b){

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

        while (j < b.length){
            c[k++] = b[j++];
        }

        while (i < a.length){
            c[k++] = a[i++];
        }

        return c;
    }
}

以上只是一种常规思路,当然你也可以先将两个数组进行合并,合并之后再进行排序输出。

posted @   LoremMoon  阅读(170)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
点击右上角即可分享
微信分享提示
主题色彩