Skip to content

Instantly share code, notes, and snippets.

@rayfix
Last active December 19, 2015 09:09
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 rayfix/5931443 to your computer and use it in GitHub Desktop.
Save rayfix/5931443 to your computer and use it in GitHub Desktop.
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