我已经实现了计算数组反转的算法(它也合并了数组),但为了使它更整洁,我想对输出进行排序和计数。
方法 *count_and_sort* 返回数组 [ number_of_inversions, [sorted_array] ]。方法inversions和 *merge_sort* 应该分别返回 number_of_inversions 和 [sorted_array] ,但我得到NoMethodError
我错过了什么?
class Array
def inversions
count_and_sort[0]
end
def merge_sort
count_and_sort[1]
end
def merge_sort!
replace merge_sort
end
private
def count_and_sort
return [0, self] if self.size <= 1
left, right = partition.with_index{ |value, index| index < self.size / 2}
left = left.count_and_sort
right = right.count_and_sort
merged = merge(left[1], right[1])
[left[0] + right[0] + merged[0], merged[1]]
end
def merge(left, right)
inversions = 0
merged = []
until left.empty? || right.empty?
if left.first < right.first
merged << left.shift
else
merged << right.shift
inversions += left.size
end
end
merged += left += right
[inversions, merged]
end
end
p [*1..20].shuffle.inversions
我尝试用
def inversions
result = self.send(:count_and_sort)
result[0]
end
但结果是一样的。
PS欢迎任何其他批评和评论;)