Modified 2 color sort
时间:2010-12-05 来源:Sun Yongyue
比如说输入{0,1,1,0,1,1,0}就变换成{0,1,0,1,0,1,1}
好的,没有现在算法,这种问题我喜欢。其实还是可以从其他算法中借鉴一些思想,还记得Knuth给的一个快排吗?
eidx = 0 // even index
oidx = 1 // odd index
while (eidx < len && oidx < len):
while (eidx < len && array[eidx] == 1) eidx += 2;
while (oidx < len && array[oidx] == 0) oidx += 2;
if (eidx < len && oidx < len) swap(eidx, oidx);
}
if (eidx < len)
{
p = eidx;
q = (len >> 1) << 1;
while (p < q)
{
while (p < q && array[p] == 1) p += 2;
while (p < q && array[q] == 0) q -= 2;
if (p < q) swap(p, q);
}
}
else if (oidx < len)
// similar to above
时间复杂度O(n),空间复杂度O(1)
排行榜 更多 +