合并排序中的逻辑流程

时间:2014-01-20 20:09:14

标签: java algorithm sorting mergesort

如何阅读和理解mergesort代码?我试图使用调试来跟踪逻辑,但似乎仍然很难弄清楚。你能为我阐明一下吗?非常感谢

 static void sort(int[]array, int[] helper, int lower, int upper){
        if(lower == upper){
            return;
        }
        // 6,5,3,1,8,7,2,4
        int mid = lower + (upper - lower) / 2;
        sort(array, helper, lower, mid);
        sort(array, helper, mid+1, upper);

        merge(array, helper, lower, mid+1, upper);

    }

2 个答案:

答案 0 :(得分:1)

以下是一些评论。另请查看此视频,它可以帮助您了解正在发生的事情。要记住的主要事情是这是一个递归算法,因此您可以通过将其分解为更小的部分并在这些较小的部分上运行相同的算法来解决它。

 static void sort(int[]array, int[] helper, int lower, int upper){        
        if(lower == upper){
            // Lower == upper, this means there is only one element, so by definition this is sorted, nothing to do just return
            return;
        }

        // Okay, we have more then one element if we are here.  Our goal here is to sort both the upper half, and lower half independently first.
        //
        // First find the mid point between the upper and lower bounds we are sorting
        // For example if we have an array [6, 5, 3, 1, 8, 7, 2, 4] with lower == 0 and upper == 7 then the mid point is 3
        // Find the mid-point of lower and upper.  This will be used to 
        int mid = lower + (upper - lower) / 2;

        // Now sort both the upper and lower half of the array recursively.
        // Array will look like this to begin with [6, 5, 3, 1, 8, 7, 2, 4]
        sort(array, helper, lower, mid);
        // After sorting from 0 to 3 it will look like this 
        // [1, 3, 5, 6, 8, 7, 2, 4]
        sort(array, helper, mid+1, upper);
        // After sorting from 4 to 7 it will look like this
        // [1, 3, 5, 6, 2, 4, 7, 8]

        // Finally merge the two sorted arrays together.  This is easier now the two halfs are sorted.
        merge(array, helper, lower, mid+1, upper);
        // After we have a sorted array
        // [1, 2, 3, 4, 5, 6, 7, 8]
 }

答案 1 :(得分:1)

这是一张实时排序的数组图片,同时显示每种排列的数组。这些都在wikipedia merge sort page

您不仅要学习排序功能,还要学习合并功能。 sort函数是函数的递归部分,而merge函数是肉和土豆;它实际上是排序部分。

例如,在下面的第一张图中,sort函数是将块拆分为4,2,然后1的组。合并函数是对这些块进行排序,比较每组的第一个值(大小) 1,2,然后4)然后将它们从最低到最高放入新的合并数组中。 enter image description here enter image description here