Last active
August 29, 2015 14:00
-
-
Save bgmarx/d5e399a9f8f4b0156b7f to your computer and use it in GitHub Desktop.
Merge Sort
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
def merge_sort(arr) | |
return arr if arr.size <= 1 | |
left, right = halve_array(arr) | |
left_part = merge_sort(left) | |
right_part = merge_sort(right) | |
array = [] | |
offset_left_part = 0 | |
offset_right_part = 0 | |
while offset_left_part < left_part.count && offset_right_part < right_part.count | |
a = left_part[offset_left_part] | |
b = right_part[offset_right_part] | |
if a <= b | |
array << a | |
offset_left_part += 1 | |
else | |
array << b | |
offset_right_part += 1 | |
end | |
while offset_left_part < left_part.count | |
array << left_part[offset_left_part] | |
offset_left_part += 1 | |
end | |
while offset_right_part < right_part.count | |
array << right_part[offset_right_part] | |
offset_right_part += 1 | |
end | |
return array | |
end | |
end | |
def halve_array(arr) | |
median = (arr.size / 2).round | |
[arr.take(median), arr.drop(median)] | |
end | |
a =[3,5,2,45,41,500,41] | |
p merge_sort(a) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment