Created
March 28, 2022 12:24
-
-
Save curipha/22df9182e133abf3be7d1a6c312c1c80 to your computer and use it in GitHub Desktop.
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
#!/usr/bin/env ruby | |
# a1 : [ int, int, ... ] | |
# a2 : [ int, int, ... ] | |
def merge(a1, a2 = nil) | |
return a1 if a2.nil? | |
r = [] | |
loop do | |
case | |
when a1.count < 1 && a2.count < 1 then break | |
when a1.count < 1 then r << a2.shift | |
when a2.count < 1 then r << a1.shift | |
when a1[0] <= a2[0] then r << a1.shift | |
when a1[0] > a2[0] then r << a2.shift | |
end | |
end | |
return r | |
end | |
def msort(arr) | |
len = arr.count | |
return arr[0] if len < 2 | |
mid = len / 2 | |
return merge( | |
msort(arr[0...mid]), | |
msort(arr[mid...len]) | |
) | |
end | |
input = ARGV.map{|v| [ v.to_i ] } # Convert to integer, non-numeric value => 0 | |
p msort(input) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment