Last active
July 13, 2019 11:51
-
-
Save pdkproitf/00a0c9e3c9c489e3be19b53282e61c90 to your computer and use it in GitHub Desktop.
Implement merge sort 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
# Algorithms: https://www.geeksforgeeks.org/merge-sort/ | |
def merge_sort(array) | |
return array if array.length <= 1 | |
mid = (array.length / 2) | |
left = merge_sort(array[0..mid - 1]) | |
right = merge_sort(array[mid..-1]) | |
merge(left, right) | |
end | |
def merge(left, right) | |
print "#{left} --- #{right}\n" | |
if left.empty? | |
right | |
elsif right.empty? | |
left | |
elsif left[0] < right[0] | |
[left[0]] + merge(left[1..left.length], right) | |
else | |
[right[0]] + merge(left, right[1..right.length]) | |
end | |
end | |
puts '------------------------------MERGE SORT SORT O(nlogn)--------------------------' | |
print merge_sort([3,7,8,4,10,16,2,1,12]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment