Skip to content

Instantly share code, notes, and snippets.

@rayfix
Last active Dec 19, 2015
Embed
What would you like to do?
Naive merge sort in ruby.
class Array
def merge_sort
c = self.count
return self if c <= 1
mid = c/2
left = self[0,mid].merge_sort
right = self[mid, mid+1].merge_sort
output = []
l = 0;
r = 0;
while (l < left.count && r < right.count)
if (left[l] < right[r])
output << left[l]
l += 1
else
output << right[r]
r += 1
end
end
output << left[l, left.count-l]
output << right[r, right.count-r]
output.flatten
end
end
a = (1..10000).to_a.shuffle
puts "Sorted: #{a.merge_sort}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment