Skip to content

Instantly share code, notes, and snippets.

@ksaynice
Forked from bgmarx/merge sort
Created May 22, 2014 23:27
Show Gist options
  • Save ksaynice/932d8ddb37067a91cb04 to your computer and use it in GitHub Desktop.
Save ksaynice/932d8ddb37067a91cb04 to your computer and use it in GitHub Desktop.
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