让我们使用来自Wikipedia的代码。您需要依靠拆分部分。拆分是在merge_sort(list m)
.. 中进行的。您需要将计数器添加为输入参数(var count
),见下文。计数器必须是count=0
。每次调用方法和 listlenght>0
时,都会将计数器增加 1。
function merge_sort(list m, var count)
// Count here
if(length(m))>0
count++;
// if list size is 0 (empty) or 1, consider it sorted and return it
// (using less than or equal prevents infinite recursion for a zero length m)
if length(m) <= 1
return m
// else list size is > 1, so split the list into two sublists
var list left, right
var integer middle = length(m) / 2
for each x in m before middle
add x to left
for each x in m after or equal middle
add x to right
// recursively call merge_sort() to further split each sublist
// until sublist size is 1
left = merge_sort(left,count)
right = merge_sort(right,count)
// merge the sublists returned from prior calls to merge_sort()
// and return the resulting merged sublist
return merge(left, right)
function merge(left, right)
var list result
while length(left) > 0 or length(right) > 0
if length(left) > 0 and length(right) > 0
if first(left) <= first(right)
append first(left) to result
left = rest(left)
else
append first(right) to result
right = rest(right)
else if length(left) > 0
append first(left) to result
left = rest(left)
else if length(right) > 0
append first(right) to result
right = rest(right)
end while
return result
对于 wikipedia 示例,您需要像这样调用伪代码merge_sort([38,27,43,3,9,82,10], 0)
。