# sort.rb
class Array
def insertion
(1..self.count).each do |i|
(i..0).each do |j|
first = j - 1
second = j
if self[second] > self[first]
swap(second, first)
end
end
end
self
end
def mergesort
return self if self.size <= 1
mid = self.size / 2
left = self[0, mid]
right = self[mid, self.size-mid]
merge_array(left.mergesort, right.mergesort)
end
# helpers
def merge_array(left, right)
sorted = []
until left.empty? or right.empty?
if left.first <= right.first
sorted << left.shift
else
sorted << right.shift
end
end
sorted.concat(left).concat(right)
end
def swap(previous, current)
copy = self[previous]
self[previous] = self[current]
self[current] = copy
end
end
我的 rspec 文件:
require './sort'
unsorted = 5000.downto(1).to_a.shuffle
describe Array, "#insertion" do
it "sorts using insertion sort" do
time = Time.now
unsorted.insertion.should eq(unsorted.sort)
puts "insertion"
puts Time.now - time
end
end
describe Array, "#merge" do
it "sorts using merge sort" do
time = Time.now
unsorted.mergesort.should eq(unsorted.sort)
puts "merge"
puts Time.now - time
end
end
我们知道插入排序应该比归并排序慢,因为插入排序的运行时间平均为 O(n^2),而归并排序为 O(n*log(n))。但是,当我运行上面的测试代码时,合并比插入慢 10 倍以上。
插入 0.001294 秒 。合并 0.017322 秒
我的猜测是我使用了一些计算量大的方法,比如shift
and concat
,但是相差 10 倍就太夸张了。
如何改进归并排序?