Skip to content

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
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
Something went wrong with that request. Please try again.