Time for an 2014 update…

This commit is contained in:
Ingy döt Net 2014-01-17 05:32:22 +00:00
parent 372c577f83
commit 09687c4926
2520 changed files with 34227 additions and 7318 deletions

View file

@ -1,34 +1,26 @@
def merge_sort(m)
if m.length <= 1
return m
end
return m if m.length <= 1
middle = m.length / 2
left = m[0,middle]
right = m[middle..-1]
middle = m.length / 2
left = m[0,middle]
right = m[middle..-1]
left = merge_sort(left)
right = merge_sort(right)
merge(left, right)
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
result = []
until left.empty? || right.empty?
if left.first <= right.first
result << left.shift
else
result << right.shift
end
unless left.empty?
result += left
end
unless right.empty?
result += right
end
result
end
result + left + right
end
ary = [7,6,5,9,8,4,3,1,2,0]
p merge_sort(ary) # => [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

View file

@ -1,36 +1,32 @@
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
return self if length <= 1
comparitor ||= lambda {|a, b| a <=> b}
middle = length / 2
left = self[0, middle].mergesort(&comparitor)
right = self[middle..-1].mergesort(&comparitor)
merge(left, right, comparitor)
end
protected
private
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)
result = []
until left.empty? || right.empty?
# change the direction of this comparison to change the direction of the sort
if comparitor[left.first, right.first] <= 0
result << left.shift
else
result << right.shift
end
end
result + left + right
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]
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"]]
ary.mergesort {|a, b| a[1] <=> b[1]}
p ary.mergesort {|a, b| a[1] <=> b[1]}
# => [["US", "Birmingham"], ["UK", "Birmingham"], ["UK", "London"], ["US", "New York"]]