合并两个有序数组(重新开始)

在看分治算法的时候,想先自己写写合并的代码,还是不熟练啊!

为了保持对代码的敏感度,要保持练习。加油!

public class JustDoIt0803 {

    /**
     * 分治算法学习前准备
     */
    public static void main(String[] args) {

        int[] x = new int[]{1,4,5,33};
        int[] y = new int[]{2,4,5,7,9,12,45,78};
        int[] z = mergeArrays(x, y);
        for (int i = 0; i < z.length; i++) {
            System.out.print(z[i] + " ");
        }
        System.out.println();
        int[] t1 = null;
        int[] t2 = null;
        System.out.println(mergeArrays(t1, t2).length);
    }
    
    /**
     * 
     * @param x a int array be sorted
     * @param y a int array be sorted
     * @return z a int array be sorted merge x and y
     * 把两个排序的数组拼接成一个排序的数组
     */
    private static int[] mergeArrays(int[] x, int [] y){
        if(x == null || y == null){
            return new int[]{};
        }
        int xl = x.length;
        int yl = y.length;
        int zl = xl + yl;
        int[] z = new int[zl];// zl代表数组元素个数
        
        if(xl == 0)
            return y;
        if(yl == 0)
            return x;
        
        int a = 0;
        int b = 0;
        
        for (int i = 0; i < zl; i++) {
            if(x[a] < y[b]){
                z[i] = x[a];
                a++;
            }else{
                z[i] = y[b];
                b++;
            }
            // 拼接尾段
            if(a >= xl){
                int tail = yl - b;
                for(int j = 0; j < tail;j++){
                    z[a+b] = y[b];
                    b++;
                }
                break;
            }
            if(b >= yl){
                int tail = xl - b;
                for(int j = 0; j < tail;j++){
                    z[a+b] = x[a];
                    a++;
                }
                break;
            }
        }
        
        return z;
    }
}

posted on 2012-08-03 23:07  每当变幻时  阅读(413)  评论(0编辑  收藏  举报

导航