Skip to content

Instantly share code, notes, and snippets.

@cody-code-wy
Last active May 25, 2016 15:33
Show Gist options
  • Save cody-code-wy/84731344e4c289ba5222a866b7cd298b to your computer and use it in GitHub Desktop.
Save cody-code-wy/84731344e4c289ba5222a866b7cd298b to your computer and use it in GitHub Desktop.
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