首页 > 代码库 > 合并排序

合并排序

温习并学习下算法,记录设计地点滴。

 

合并排序:两个有序地数组合并成一个有序地数组。

以前我面试还问到这个问题,两个有序数组合并要求写出最优算法,我给出地是写法如下,某种意义来说代码写的不是很简练,没办法!面试没过/(ㄒoㄒ)/~~

package test;

import java.util.Arrays;

public class MergeSortPolicy {

    public int[] sort1(int[] a, int[] b) {
        
        int j=0;
        int[] c = new int[a.length+b.length];
        
        for (int i=0; i<a.length; i++) {
            
            int value =http://www.mamicode.com/ a[i];
            while(value >= b[j]) {
                
                c[i+j] = b[j];
                j++;
                if (j==b.length) {
                    break;
                }
            }
            c[i+j] = value;
            
        }
        
        return c;
    }
    
    public static void main(String[] args) {
        
        MergeSortPolicy sortPolicy = new MergeSortPolicy();
        int[] toSortArrA = {-1,1,2,9,33,100};
        int[] toSortArrB = {0,21,68,73};
        System.out.println(Arrays.toString(sortPolicy.sort1(toSortArrA, toSortArrB)));
    }
}

执行结果: [-1, 0, 1, 2, 9, 21, 33, 68, 73, 100]

 

代码比较简练地写法如下,但我个人觉得其实没啥意义,单层循环和双层循环嵌套地执行步骤是一样地:

package test;

import java.util.Arrays;

public class MergeSortPolicy {

    public int[] sort2(int[] a, int[] b) {
        
        int[] c = new int[a.length+b.length];
        int i=0,j=0,k=0;
        
        while (i<=a.length-1 && j<=b.length-1) {
            if (a[i] <= b[j]) {
                c[k] = a[i];
                i++;
            } else {
                c[k] = b[j];
                j++;
            }
            k++;
        }
        
        // copyRange
        for (; i<=a.length-1; i++,k++) {
            c[k] = a[i];
        }
        
        // copyRange
        for (; j<=b.length-1; j++,k++) {
            c[k] = b[j];
        }
        return c;
    }
    
    public static void main(String[] args) {
        
        MergeSortPolicy sortPolicy = new MergeSortPolicy();
        int[] toSortArrA = {-1,1,2,9,33,100};
        int[] toSortArrB = {0,21,68,73};
        // 执行结果
        System.out.println(Arrays.toString(sortPolicy.sort2(toSortArrA, toSortArrB)));
    }
}

 

合并排序