Created
April 14, 2013 21:53
-
-
Save raphaelcm/5384397 to your computer and use it in GitHub Desktop.
O(n*log n) sorting algorithms: Quicksort and Mergesort. Implemented in Ruby
This file contains 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
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 |
This file contains 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
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