1. 程式人生 > >對倆個有序數組合並排序

對倆個有序數組合並排序

/**
 * 演算法學習 -- 兩個有序數組合並排序
 */
public class MergeArrayAndOrder {

    public static void main(String[] args) {
        int[] a = new int[]{1,3,5,7,9,16,17};
        int[] b = new int[]{0,2,4,6,8,10,11,12,13,14,18,19};
        int[] c = MergeArrayAndOrder.mergeOrder(a,b);
        for(int i : c){
            System.out.println(i);
        }
    }

    public static int[] mergeOrder(int[] arr1,int[]arr2){
        int[] result = new int[arr1.length + arr2.length];
        int m = 0;
        int n = 0;
        for (int i=0;i<result.length;i++){
            if(m == arr1.length){
                result[i] = arr2[n++];
            }else if(n == arr2.length){
                result[i] = arr1[m++];
            }else {
                if(arr1[m]<arr2[n]){
                    result[i] = arr1[m++];
                }else{
                    result[i] = arr2[n++];
                }
            }
        }
        return result;
    }
}