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

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

 

    原文作者:会飞的小猪象
    原文地址: https://blog.csdn.net/qq_21036901/article/details/81134614
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞