Skip to content

Instantly share code, notes, and snippets.

@paaloeye
Created August 17, 2012 00:27
Show Gist options
  • Save paaloeye/3374782 to your computer and use it in GitHub Desktop.
Save paaloeye/3374782 to your computer and use it in GitHub Desktop.
Naive implementation of merge sort
require 'pp'
def merge_sort(array,dir = :ask)
pp array if $VERBOSE
raise ArgumentError, "direction must be :ask or :desk symbol" unless [:ask,:desk].include? dir
return array if array.count == 1
array.reverse!
middle = array.count / 2
right, left = array[0...middle].reverse, array[middle..-1].reverse
pp [left,right] if $VERBOSE
right, left = merge_sort(right, dir), merge_sort(left, dir)
merge(left,right,dir)
end
def merge(left,right,dir)
pp [left,right] if $VERBOSE
action = case dir
when :ask
:<
when :desk
:>
end
result = []
until left.empty? or right.empty?
el = if left.first.send(action,right.first)
found = left.first
left.delete(found)
left.compact!
found
else
found = right.first
right.delete(found)
right.compact!
found
end
result << el
if left.empty?
return result + right
elsif right.empty?
return result + left
end
end
end
pp merge_sort(eval(ARGV[0]),eval(ARGV[1]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment