2020-02-09 15:53:12 +01:00
|
|
|
def merge_sort(array)
|
|
|
|
return array if array.length <= 1
|
2021-02-07 08:05:54 +01:00
|
|
|
|
2020-02-09 15:53:12 +01:00
|
|
|
mid = array.length / 2
|
|
|
|
first_array = array.slice(0..mid - 1)
|
|
|
|
second_array = array.slice(mid..-1)
|
|
|
|
|
|
|
|
first_array = merge_sort first_array
|
|
|
|
second_array = merge_sort second_array
|
|
|
|
|
|
|
|
# merge
|
|
|
|
result = []
|
2021-02-07 08:05:54 +01:00
|
|
|
until first_array.empty? && second_array.empty?
|
2020-02-09 15:53:12 +01:00
|
|
|
if first_array.empty?
|
|
|
|
result.concat(second_array)
|
|
|
|
second_array.clear
|
|
|
|
elsif second_array.empty?
|
|
|
|
result.concat(first_array)
|
|
|
|
first_array.clear
|
|
|
|
else
|
2021-02-07 08:05:54 +01:00
|
|
|
result << if first_array.first < second_array.first
|
|
|
|
first_array.shift
|
|
|
|
else
|
|
|
|
second_array.shift
|
|
|
|
end
|
2020-02-09 15:53:12 +01:00
|
|
|
end
|
|
|
|
end
|
|
|
|
result
|
|
|
|
end
|
|
|
|
|
2021-02-16 18:31:11 +01:00
|
|
|
if $0 == __FILE__
|
|
|
|
puts 'Enter a list of numbers separated by space'
|
|
|
|
|
|
|
|
list = gets.split.map(&:to_i)
|
|
|
|
p merge_sort(list)
|
|
|
|
end
|