归并排序 java 实现

来源:互联网 发布:卸载windows defender 编辑:程序博客网 时间:2024/06/05 07:53
/**     * 归并排序 两个数组都是有序的 否则需要先先排序     * @param a     * @param b     */    private static void mergerSort(int [] a,int [] b) {        int[] tempArray = new int[a.length+b.length];//创建临时接受数组        int tempCounter = 0;        int firstIndex=0, secondIndex=0;        while((firstIndex<a.length)&&(secondIndex<b.length)){            if (a[firstIndex] < b[secondIndex]) {                tempArray[tempCounter] = a[firstIndex];                tempCounter++;                firstIndex++;            }            else if (a[firstIndex] > b[secondIndex]) {                tempArray[tempCounter] = b[secondIndex];                tempCounter++;                secondIndex++;            }            else {                tempArray[tempCounter] = a[firstIndex];                firstIndex++;                tempCounter++;            }        }        /**         * 下面两种情况是当有一个数组已经完全放入了temp数组里面           * 已经失去比较对象,接下来的数字肯定是比前一个已经完全放入数组的最大的数还大,所以直接拷贝就可以了。         */        while (secondIndex < b.length) {                tempArray[tempCounter] = b[secondIndex];                secondIndex++;                tempCounter++;        }        while (firstIndex<a.length) {            tempArray[tempCounter] = a[firstIndex];            firstIndex++;            tempCounter++;        }        for (int j = 0; j < tempArray.length; j++) {            System.out.print(tempArray[j]+" ");        }    }    public static void main(String[] args) throws Exception {        int[] a  = new int[]{1,2,4,9};        int[] b  = new int[]{2,4,8};        mergerSort(a, b);    }

运行结果是:1 2 4 4 8 9

原创粉丝点击