, (n/2) th (n/2) th . SO.
, , , , .
, , (n/2): " " (S) " " ( L), :
- , e.
- S, S .
- S , (S | e) ( ) ( impedlemented S, , e, , e, ) L. S, e S, .
- L , (L | e) , e L, e .
I believe this is O (n) time; someone correct me if I am wrong. The worst scenario I could imagine was sorting the original sequence in descending order.
ruby implementation (with lots of inactivity shortcuts):
def split_into_halves to_split
s = []
l = []
medianlimit = to_split.size/2
for e in to_split
if s.size < medianlimit
s.push(e)
else
if s.max >= n
max = s.max
s.delete max
s.push(e)
else
max = e
end
if l.size < medianlimit
l.push(max)
elsif l.max >= max
l.delete l.max
l.push(max)
end
end
end
return [s,l]
end
k = [2,3,6,7,1,4,5]
split_into_halves(k)
source
share