两个有序数组合并最快的方法

4 篇文章 0 订阅
/**
* 该算法时间复杂度为O(m+n),m和n为两个数组长度
*/
public class DoubleSort {
 
    public static int[] sort(int[] one, int[] two){
        int onesize = one.length;
        int twosize = two.length;
        int threesize = onesize + twosize;
        int[] three = new int[threesize];
        int i = 0;
        int j = 0;
        for(int t = 0; t < threesize; t++){
            if(i >= onesize){   //如果一数组比较完了,直接把二数组后面的数,排序到后面
                three[t] = two[j++];
            }else if(j >= twosize){  //二数组比较完了,直接把一数组后面的数,排序到后面
                three[t] = one[i++];
            }else{
                if(one[i] <= two[j]){//一数组往后遍历,二数组不变,小于等于则把一数组的数放入新数组
                    three[t] = one[i++];
                }else {//大于则把二数组的数放入新数组
                    three[t] = two[j++];
                }
            }
        }
        return three;
    }
 
    public static void main(String[] args){
        int[] o = {1,3,5,7,9,11,12};
        int[] t = {2,4,6,8,10};
        int[] th = sort(o,t);
        System.out.println(Arrays.toString(th));
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值