Skip to content

Instantly share code, notes, and snippets.

@mindplace
Created February 26, 2016 23:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mindplace/c7620a8a74a2e85be1b1 to your computer and use it in GitHub Desktop.
Save mindplace/c7620a8a74a2e85be1b1 to your computer and use it in GitHub Desktop.
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