Created
February 13, 2017 18:37
-
-
Save diegocasmo/b330010bd891c5581ee257f9aac87419 to your computer and use it in GitHub Desktop.
An implementation of the Merge Sort algorithm in Ruby
This file contains hidden or 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
class MergeSort | |
# Sorts an array using the merge sort algorithm | |
def sort(arr) | |
length = arr.length | |
if length > 1 | |
mid = (length/2).floor | |
return merge(sort(arr[0..(mid - 1)]), sort(arr[mid..length])) | |
else | |
return arr | |
end | |
end | |
private | |
# Merges two array in sorted order | |
def merge(left, right) | |
if left.empty? | |
return right | |
elsif right.empty? | |
return left | |
elsif left.first < right.first | |
return [left.first].concat(merge(left.drop(1), right)) | |
else | |
return [right.first].concat(merge(left, right.drop(1))) | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Tests for this class can be found here: https://gist.github.com/diegocasmo/cca7c07152c611dde2cd376081d428cc