レゴで遊んでいるときに、スタックの両端に収まらないピースに遭遇するまで、常に小さいピースを大きなピースの上に積み重ねるという考えに基づいて、次の並べ替えアルゴリズムを考案しました。
私の最初の印象は、ストランドソートに似ているため、最良の場合の動作は O(n) であり、最悪の場合の動作は O(n^2) であるというものですが、大学でアルゴリズム分析を行ってからかなり時間が経ちました。その平均的な行動が何であるかはわかりません。ストランド ソートの平均 O(n^2) よりも優れているはずですが、それを証明する方法やそれが何であるかはわかりません。
私の実装では、連結リストを使用して両端での挿入を許可していますが、deque も同様に機能します。以下は説明の便宜上 Python コードですが、C++ 版の方が効率的です。
import math
def merge(x, y):
output = []
xp = 0
yp = 0
if len(y) == 0 or len(x) == 0 or y[0] > x[-1]:
return x + y
elif x[0] > y[-1]:
return y + x
while xp < len(x) and yp < len(y):
if x[xp] < y[yp]:
output.append(x[xp])
xp = xp + 1
else:
output.append(y[yp])
yp = yp + 1
if xp < len(x):
output = output + x[xp:]
elif yp < len(y):
output = output + y[yp:]
return output
def treeMerge(heads, accum):
currHead = 0
while heads[currHead] is not None:
accum = merge(heads[currHead], accum)
heads[currHead] = None
currHead = currHead + 1
heads[currHead] = accum
return heads
def legoSort(input):
heads = [None] * int(math.log(len(input), 2) + 1)
accum = []
for i in input:
# can be <= for speed at the cost of sort stability
if len(accum) == 0 or i < accum[0]:
accum.insert(0,i)
elif i >= accum[-1]:
accum.append(i)
else:
heads = treeMerge(heads, accum)
accum = [i]
for i in heads:
if i is not None:
accum = merge(accum, i)
return accum