【发布时间】:2015-01-09 19:12:10
【问题描述】:
我正在做奥丁计划。练习题是:使用递归创建归并排序算法。以下是根据某人的解决方案修改的:
def merge_sort(arry)
# kick out the odds or kick out of the recursive splitting?
# I wasn't able to get the recombination to work within the same method.
return arry if arry.length == 1
arry1 = merge_sort(arry[0...arry.length/2])
arry2 = merge_sort(arry[arry.length/2..-1])
f_arry = []
index1 = 0 # placekeeper for iterating through arry1
index2 = 0 # placekeeper for iterating through arry2
# stops when f_arry is as long as combined subarrays
while f_arry.length < (arry1.length + arry2.length)
if index1 == arry1.length
# pushes remainder of arry2 to f_arry
# not sure why it needs to be flatten(ed)!
(f_arry << arry2[index2..-1]).flatten!
elsif index2 == arry2.length
(f_arry << arry1[index1..-1]).flatten!
elsif arry1[index1] <= arry2[index2]
f_arry << arry1[index1]
index1 += 1
else
f_arry << arry2 [index2]
index2 += 1
end
end
return f_arry
end
第一行
return arry if arry.length == 1是否将其从数组的递归拆分中踢出,然后绕过方法的递归拆分部分返回重组部分?似乎它应该在它递归到该部分后继续重新拆分它。为什么一定要
flatten-ed?
【问题讨论】: