Skip to content

Instantly share code, notes, and snippets.

@daifu
Created July 21, 2015 18:51
Show Gist options
  • Save daifu/d9cef0bad46e31f85da6 to your computer and use it in GitHub Desktop.
Save daifu/d9cef0bad46e31f85da6 to your computer and use it in GitHub Desktop.
Mergesort in Ruby
=begin
Merge sort in ruby
Referrence
https://en.wikipedia.org/wiki/Merge_sort
Big O complexity
Time complexity (Average, Best, Worest cases): O(n log(n))
Space complexity: O(n)
=end
class MergeSort
# sort the array in ascending order with merge sort
#
# @params array [Array<Fixnum>]
# @returns [Array<Fixnum>] sorted array
def self.sort(array)
return array if array.size == 1
size = array.size
half_index = (size / 2.0).floor
left_ary = sort(array[0...half_index])
right_ary = sort(array[half_index...size])
merge_sorted_arrays(left_ary, right_ary)
end
private
# Merge 2 sorted arrays, Time: O(n), Space: O(n)
#
# @params ary1 [Array<Fixnum>] sorted array 1
# @params ary2 [Array<Fixnum>] sorted array 2
# @returns [Array<Fixnum>] sotred array that merged array 1 and array 2
def self.merge_sorted_arrays(ary1, ary2)
ary = []
index1 = 0
index2 = 0
while(index1 < ary1.size || index2 < ary2.size)
if index1 == ary1.size
ary += ary2[index2...ary2.size]
index2 = ary2.size
break
end
if index2 == ary2.size
ary += ary1[index1...ary1.size]
index1 = ary1.size
break
end
if ary1[index1] < ary2[index2]
ary << ary1[index1]
index1 += 1
elsif ary1[index1] > ary2[index2]
ary << ary2[index2]
index2 += 1
else
ary << ary1[index1]
ary << ary2[index2]
index1 += 1
index2 += 1
end
end
return ary
end
end
ary = [6, 5, 3, 1, 8, 7, 2, 4]
print MergeSort.sort(ary)
puts
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment