Last active
May 25, 2016 15:34
-
-
Save cody-code-wy/b73b26a656e28a004f5fd622cebb0df4 to your computer and use it in GitHub Desktop.
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 mergesort(array) | |
if array.count <= 1 | |
return array #Sorted! | |
end | |
half = array.count / 2 | |
a = mergesort(array.slice(0,half)) | |
b = mergesort(array.slice(half,array.count - half)) | |
array = [] #Empty it to start sortinng | |
a_off = 0 | |
b_off = 0 | |
while a_off < a.count && b_off < b.count | |
num_a = a[a_off] | |
num_b = b[b_off] | |
put_largest(array,num_a,num_b) ? a_off += 1 : b_off += 1 | |
end | |
fill_from(array,a,a_off) | |
fill_from(array,b,b_off) | |
return array | |
end | |
def put_largest(dest,a,b) | |
if a <= b | |
dest << a | |
return true | |
else | |
dest << b | |
return false | |
end | |
end | |
def fill_from(dest,src,start) | |
while start < src.count | |
dest << src[start] | |
start += 1 | |
end | |
end | |
puts mergesort [9,8,7,6,5,4,3,2,1] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment