Another update from ingydotnet^djgoku

This commit is contained in:
Ingy döt Net 2015-11-18 06:14:39 +00:00
parent 91df62d461
commit 948b86eafa
7604 changed files with 108452 additions and 22726 deletions

View file

@ -2,22 +2,15 @@ def merge_sort(m)
return m if m.length <= 1
middle = m.length / 2
left = m[0..middle - 1]
right = m[middle..-1]
left = merge_sort(left)
right = merge_sort(right)
left = merge_sort(m[0...middle])
right = merge_sort(m[middle..-1])
merge(left, right)
end
def merge(left, right)
result = []
until left.empty? || right.empty?
if left.first <= right.first
result << left.shift
else
result << right.shift
end
result << (left.first<=right.first ? left.shift : right.shift)
end
result + left + right
end

View file

@ -1,9 +1,9 @@
class Array
def mergesort(&comparitor)
return self if length <= 1
comparitor ||= lambda {|a, b| a <=> b}
comparitor ||= proc{|a, b| a <=> b}
middle = length / 2
left = self[0..middle - 1].mergesort(&comparitor)
left = self[0...middle].mergesort(&comparitor)
right = self[middle..-1].mergesort(&comparitor)
merge(left, right, comparitor)
end
@ -28,5 +28,7 @@ p ary.mergesort # => [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
p 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"]]
p ary.mergesort
# => [["UK", "Birmingham"], ["UK", "London"], ["US", "Birmingham"], ["US", "New York"]]
p ary.mergesort {|a, b| a[1] <=> b[1]}
# => [["US", "Birmingham"], ["UK", "Birmingham"], ["UK", "London"], ["US", "New York"]]