我很难理解自下而上合并排序算法的伪代码。
从概念上讲,我有点理解正在发生的事情。
我正在查看此网站的伪代码 - http://www.algorithmist.com/index.php/Merge_sort
Input: array a[] indexed from 0 to n-1.
m = 1
while m < n do
i = 0
while i < n-m do
merge subarrays a[i..i+m-1] and a[i+m .. min(i+2*m-1,n-1)] in-place.
i = i + 2 * m
m = m * 2
但是在第一次循环后我迷路了!递归实现对我来说更直观,但迭代方法让我失望!如果任何人都可以在python或c ++中实现它,并解释每个步骤,以及每个变量的用途,我将非常感激。
干杯!
答案 0 :(得分:2)
m
是一起排序的元素数。它从1个元素开始,并保持加倍,直到我们将列表的一半与另一半合并。
n
是列表的大小。
i
是要合并的第一个子阵列的第一个元素的索引。
i + m
是第二个子阵列合并的第一个元素。
这是一个简单的例子。
Say I have the following n=5 list: a = [3,1,2,5,4]
m = 1:
Merge each 1 element subarray with its 1 element neighbor subarray
i = 0:
Merge [3] and [1] -> [1,3]
a is now [1,3,2,5,4]
i = 2:
Merge [2] and [5] -> [2,5]
a is now [1,3,2,5,4]
m = 2:
Merge each 2 element subarray with its 2 element neighbor subarray
i = 0:
Merge [1,3] and [2,5] -> [1,2,3,5]
a is now [1,2,3,5,4]
m = 4:
Merge each 4 element subarray with its 4 element neighbor subarray
i = 0:
Merge [1,2,3,5] and [4]
a is now [1,2,3,4,5]. We're done sorting.