Created
September 17, 2010 19:38
-
-
Save iangreenleaf/584799 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
# Mergesort | |
# precondition: no nils in the array | |
def sort some_array | |
return some_array if some_array.length == 1 | |
half_length = some_array.length / 2 | |
first_half = sort(some_array[0,half_length]) | |
second_half = sort(some_array[half_length, some_array.length - half_length]) | |
result = [] | |
a = b = 0 | |
while a < first_half.length || b < second_half.length | |
a_val = first_half[a] | |
b_val = second_half[b] | |
if b_val.nil? || (!a_val.nil? && a_val < b_val) | |
result << a_val | |
a += 1 | |
else | |
result << b_val | |
b += 1 | |
end | |
end | |
result | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment