Created
February 26, 2016 23:21
-
-
Save mindplace/c7620a8a74a2e85be1b1 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
def merge_sort(array) | |
total_length = array.length | |
size = 2 | |
while size < total_length + 1 | |
sorted_array = [] | |
array.each_slice(size).to_a.each do |group| | |
slice1 = group[0...(group.length / 2)] | |
slice2 = group[(group.length / 2)..-1] | |
combined = [] | |
while slice1.length > 0 || slice2.length > 0 | |
if slice1.empty? == false | |
if slice2.empty? || slice1.first < slice2.first | |
combined << slice1.shift | |
elsif slice1.first == slice2.first | |
combined << slice1.shift | |
combined << slice2.shift | |
else | |
combined << slice2.shift | |
end | |
elsif slice2.empty? == false | |
if slice1.empty? || slice2.first < slice1.first | |
combined << slice2.shift | |
elsif slice1.first == slice2.first | |
combined << slice1.shift | |
combined << slice2.shift | |
else | |
combined << slice1.shift | |
end | |
end | |
end | |
sorted_array << combined | |
end | |
array = sorted_array.flatten | |
size += 2 | |
end | |
p array | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment