Skip to content

Instantly share code, notes, and snippets.

@raphaelcm
Created April 14, 2013 21:53
Show Gist options
  • Save raphaelcm/5384397 to your computer and use it in GitHub Desktop.
Save raphaelcm/5384397 to your computer and use it in GitHub Desktop.
O(n*log n) sorting algorithms: Quicksort and Mergesort. Implemented in Ruby
module Mergesort
def self.sort(array)
return array if array.length <= 1
middle = array.length/2
left = sort(array[0..(middle-1)])
right = sort(array[middle..-1])
merge(left, right)
end
def self.merge(left, right)
result = []
while(left.length > 0 || right.length > 0) do
if left.length > 0 && right.length > 0
if left.first <= right.first
result << left.shift
else
result << right.shift
end
elsif left.length > 0
result << left.shift
elsif right.length > 0
result << right.shift
end
end
result
end
end
module Quicksort
module Simple
def self.sort(array)
return array if array.length <= 1
less = []
greater = []
pivot = array.shift
array.each do |elem|
if elem <= pivot
less << elem
else
greater << elem
end
end
sort(less) + [pivot] + sort(greater)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment