最快实现两个有序数组合并为一个有序数组

本文介绍了一种将两个整数数组合并并进行排序的算法,时间复杂度为O(m+n)。该算法通过比较两个数组中的元素并将较小的元素依次放入新数组中,直至所有元素被排序。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 该算法时间复杂度为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));
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值