all tasks

This commit is contained in:
Ingy döt Net 2013-04-11 01:07:29 -07:00
parent b83f433714
commit 68f8f3e56b
14735 changed files with 178959 additions and 0 deletions

View file

@ -0,0 +1,34 @@
def merge_sort(m)
if m.length <= 1
return m
end
middle = m.length / 2
left = m[0,middle]
right = m[middle..-1]
left = merge_sort(left)
right = merge_sort(right)
merge(left, right)
end
def merge(left, right)
result = []
until left.empty? || right.empty?
# change the direction of this comparison to change the direction of the sort
if left.first <= right.first
result << left.shift
else
result << right.shift
end
end
unless left.empty?
result += left
end
unless right.empty?
result += right
end
result
end

View file

@ -0,0 +1,36 @@
class Array
def mergesort(&comparitor)
if length <= 1
self
else
unless comparitor
comparitor = lambda {|a, b| a <=> b}
end
middle = length / 2
left = self[0, middle].mergesort(&comparitor)
right = self[middle..-1].mergesort(&comparitor)
merge(left, right, comparitor)
end
end
protected
def merge(left, right, comparitor)
if left.empty?
right
elsif right.empty?
left
elsif comparitor.call(left.first, right.first) <= 0
[left.first] + merge(left[1..-1], right, comparitor)
else
[right.first] + merge(left, right[1..-1], comparitor)
end
end
end
ary = [7,6,5,9,8,4,3,1,2,0]
ary.mergesort # => [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
ary.mergesort {|a, b| b <=> a} # => [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
ary = [["UK", "London"], ["US", "New York"], ["US", "Birmingham"], ["UK", "Birmingham"]]
ary.mergesort {|a, b| a[1] <=> b[1]}
# => [["US", "Birmingham"], ["UK", "Birmingham"], ["UK", "London"], ["US", "New York"]]