Skip to content

Instantly share code, notes, and snippets.

@diegocasmo
Created February 13, 2017 18:37
Show Gist options
  • Save diegocasmo/b330010bd891c5581ee257f9aac87419 to your computer and use it in GitHub Desktop.
Save diegocasmo/b330010bd891c5581ee257f9aac87419 to your computer and use it in GitHub Desktop.
An implementation of the Merge Sort algorithm in Ruby
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
@diegocasmo
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment