Skip to content

Instantly share code, notes, and snippets.

@denkiwakame
Created March 10, 2014 14:57
Show Gist options
  • Save denkiwakame/9466549 to your computer and use it in GitHub Desktop.
Save denkiwakame/9466549 to your computer and use it in GitHub Desktop.
てきとーに
#!/usr/bin/ruby
def merge(ary1,ary2)
idx1 = 0
idx2 = 0
result = Array.new
while result.length < ary1.length + ary2.length
ary1val = idx1 <= ary1.length-1 ? ary1[idx1] : -1
ary2val = idx2 <= ary2.length-1 ? ary2[idx2] : -1
if ary1val > ary2val
result.push ary1val
idx1 += 1
else
result.push ary2val
idx2 += 1
end
end
return result
end
def mergeSort(first, last, ary)
if first >= last
return
end
mid = ( first + last ) / 2
mergeSort(first, mid, ary)
mergeSort(mid+1, last, ary)
buf1 = ary[first..mid]
buf2 = ary[mid+1..last]
ary[first..last] = merge(buf1,buf2)
end
N = 16
$X = Array.new(N)
for i in 0..N-1
$X[i] = rand(N)
end
p $X
mergeSort(0, $X.length-1, $X)
p $X
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment