Skip to content

Instantly share code, notes, and snippets.

@arya
Created January 28, 2010 20:11
Show Gist options
  • Save arya/289094 to your computer and use it in GitHub Desktop.
Save arya/289094 to your computer and use it in GitHub Desktop.
class MergeColumn
def initialize(array)
@array = array
@index = 0
end
def value
@array[@index]
end
def empty?
@index > @array.size - 1
end
def pop
@index += 1
@array[@index - 1]
end
def <=>(o)
self.value <=> o.value
end
end
class Array
def merge_sort(n = nil)
columns = self.collect { |e| MergeColumn.new(e) }
result = []
while !columns.empty? && (n.nil? || n > result.size)
col = columns.shift
result << col.pop
unless col.empty?
columns.push(col)
# this part could be an insertion sort instead of a full resort every time
columns.sort!
end
end
result
end
end
unsorted = (1..100).to_a.inject({}) do |h, k|
h[k] = []
# 500.times { h[k] << {"created_at" => Time.at(rand(Time.now.to_i))} }
# h[k].sort! {|a, b| a["created_at"] <=> b["created_at"]}
500.times { h[k] << rand(Time.now.to_i) }
h[k].sort!
h
end
require 'benchmark'
flat = unsorted.values.flatten
vals = unsorted.values
# puts unsorted.values.merge_sort(10)
# puts
# puts unsorted.values.flatten.sort[0, 10]
Benchmark.bmbm do |x|
x.report("merge") { 100.times { unsorted.values.merge_sort(10) } }
x.report("ruby sort") { 100.times { flat.sort[0,10] } }
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment