Created
September 6, 2013 18:17
-
-
Save wrhall/6467755 to your computer and use it in GitHub Desktop.
Sample code from a blog post I wrote
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(a) | |
return a if a.length <= 1 | |
first_half = a.first(a.length / 2) | |
second_half = a.last(a.length - a.length / 2) | |
sorted_first_half = merge_sort(first_half) | |
sorted_second_half = merge_sort(second_half) | |
merge_step(sorted_first_half, sorted_second_half) | |
end | |
def merge_step(l, r) | |
merged = [] | |
while l.any? and r.any? | |
if l.first < r.first | |
merged << l.shift | |
else | |
merged << r.shift | |
end | |
end | |
merged + l + r | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment