public
Created

  • Download Gist
gistfile1.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
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

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.