(Java)两个有序数组合并成新的有序数组

public static void test(int[] num1,int[] num2){
        int p1=0;
        int p2=0;
        int p=0;
        int [] res = new int[num1.length+num2.length];
        while (p1<num1.length && p2<num2.length){
            res[p++]=num1[p1]<num2[p2]?num1[p1++]:num2[p2++];
 
        }
        if(p1<num1.length){
            //参数 :复制来源数组,来源数组的开始下标,复制到的目标数组,目标数组的开始下标,复制的长度
            System.arraycopy(num1,p1,res,p1 + p2, num1.length+num2.length - p1 - p2);
        }
 
        if(p2<num2.length){
            System.arraycopy(num2,p2,res,p1 + p2, num1.length+num2.length - p1 - p2);
        }
 
        for (int i=0;i<res.length;i++){
            System.out.println(res[i]);
        }
 
    }
 
    public static void main(String[] args) {
        int[] a={1,4,7};
 
        int[] b={3,6,9,11};
 
        test(b,a);
    }
}
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容