二路归并排序的java实现

转载请注明出处 http://www.cnblogs.com/dongxiao-yang/p/6410775.html 

参考引言:在排序算法中快速排序的效率是非常高的,但是还有种排序算法的效率可以与之媲美,那就是归并排序;归并排序和快速排序有那么点异曲同工之妙,快速排序:是先把数组粗略的排序成两个子数组,然后递归再粗略分两个子数组,直到子数组里面只有一个元素,那么就自然排好序了,可以总结为先排序再递归;归并排序:先什么都不管,把数组分为两个子数组,一直递归把数组划分为两个子数组,直到数组里只有一个元素,这时候才开始排序,让两个数组间排好序,依次按照递归的返回来把两个数组进行排好序,到最后就可以把整个数组排好序;

 

public class mergesortutil {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        int[] a = new int[] { 11,9,7,5,3,1,12,10,8,6,4,2 };
        

        int[] tmp = new int[a.length];
        mergesort(a,0,a.length-1,tmp);
    }

    private static void mergearray(int[] array, int start, int middle, int end,int[] tmp) {

        int first = start;
        int second = middle + 1;
        int index = start;


        while ((first <= middle) && (second <= end)) {
            if (array[first] >= array[second])
                tmp[index++] = array[second++];
            else
                tmp[index++] = array[first++];
        }
        while (first <= middle)
            tmp[index++] = array[first++];
        while (second <= end)
            tmp[index++] = array[second++];

        for (first = start; first <= end; first++)
            array[first] = tmp[first];
        
        
        System.out.println("merge is "+Arrays.toString(array));

    }

    public static void mergesort(int[] array, int start, int end,int[] tmp) {

        if (start >= end)
            return;
        int middle = ((end + start) >> 1);
        mergesort(array, start, middle,tmp);// 递归划分左边的数组
        mergesort(array, middle + 1, end,tmp);// 递归划分右边的数组
        mergearray(array, start, middle, end,tmp);// 对有序的两个数组进行合并成一个有序的数组
    }

}

 

程序调试输出如下

merge is [9, 11, 7, 5, 3, 1, 12, 10, 8, 6, 4, 2]

merge is [7, 9, 11, 5, 3, 1, 12, 10, 8, 6, 4, 2]

merge is [7, 9, 11, 3, 5, 1, 12, 10, 8, 6, 4, 2]

merge is [7, 9, 11, 1, 3, 5, 12, 10, 8, 6, 4, 2]

merge is [1, 3, 5, 7, 9, 11, 12, 10, 8, 6, 4, 2]

merge is [1, 3, 5, 7, 9, 11, 10, 12, 8, 6, 4, 2]

merge is [1, 3, 5, 7, 9, 11, 8, 10, 12, 6, 4, 2]

merge is [1, 3, 5, 7, 9, 11, 8, 10, 12, 4, 6, 2]

merge is [1, 3, 5, 7, 9, 11, 8, 10, 12, 2, 4, 6]

merge is [1, 3, 5, 7, 9, 11, 2, 4, 6, 8, 10, 12]

merge is [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]

 

调试过程输出结果有助于更好的理解排序过程,整个排序在数组划分到最小长度后不断进行局部排序和局部合并排序,最终合并为全数组。

 

 

参考资料 

归并排序的原理及时间复杂度

白话经典算法系列之五 归并排序的实现

排序算法之 归并排序 及其时间复杂度和空间复杂度

posted @ 2017-02-17 17:50  sanmutongzi  阅读(2955)  评论(0编辑  收藏  举报