Last active
August 29, 2015 14:07
-
-
Save JohnathanWeisner/6b29aa7f49ac482c4eab to your computer and use it in GitHub Desktop.
Ruby Merge Sort
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def merge_sort(ary) | |
size = ary.size | |
return ary if size <= 1 | |
mid = size/2 | |
left, right = ary[0..mid-1], ary[mid..-1] | |
left, right = merge_sort(left), merge_sort(right) | |
merge(left, right) | |
end | |
def merge(left, right) | |
result = [] | |
while left.size > 0 || right.size > 0 | |
if left.size > 0 && right.size > 0 | |
result << ((left[0] <= right[0]) ? left.shift : right.shift) | |
elsif left.size > 0 | |
result << left.shift | |
elsif right.size > 0 | |
result << right.shift | |
end | |
end | |
result | |
end | |
p merge_sort([*1..100].shuffle) == [*1..100] | |
p merge_sort([*1..10000].shuffle) == [*1..10000] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment