我只是想到了一种有趣的方式来做一个排序。我确信有人曾经想过它,但我从来没有见过它。它分两步走:
1-遍历输入列表,将按顺序排列的项目(不一定是连续的)排出到分箱中。为每次传递创建一个bin,直到列表为空。
2-使用标准合并(重复选择最低的第一个元素)合并排序后的二进制文件,
这是我用Python制作的原型。下面的输出可能更具启发性。
items = len(unsorted)
sortedBins = []
# Pull out bins of sorted numbers, until the unsorted list is depleted:
while( len(unsorted) > 0 ):
print "Unsorted list: " + `unsorted`
highest = float("-inf")
newBin = []
i = 0
while( i < len(unsorted) ):
# Find items in unsorted list that are in order, pop them out:
if( unsorted[i] >= highest ):
highest = unsorted[i]
newBin.append( unsorted.pop(i) )
i=i+1
sortedBins.append(newBin)
print "bin[%i]: "%(len(sortedBins)-1) + `newBin`
# Merge all of the sorted bins together:
sorted = []
while( len(sorted) < items ):
lowBin = 0
for j in range( 0, len(sortedBins) ):
if( sortedBins[j][0] < sortedBins[lowBin][0] ):
lowBin = j
print "lowBin: %i: %i" % (lowBin, sortedBins[lowBin][0])
sorted.append( sortedBins[lowBin].pop(0) )
if( len(sortedBins[lowBin]) == 0 ):
del sortedBins[lowBin]
print "sorted:" + `sorted`如果我不疯狂(即每个循环n(n + 1)/ 2),似乎最坏的情况(完全颠倒的列表)将花费n(n + 1)次。最好的情况(已经排序的列表)需要2 * n次。
编辑:它现在运行,所以停止抱怨。这里是输出,它进一步演示了它的工作原理:
Unsorted list: [1, 4, 3, 8, 3, 7, 9, 4, 8, 9, 3]
bin[0]: [1, 3, 3, 9, 9]
Unsorted list: [4, 8, 7, 4, 8, 3]
bin[1]: [4, 7, 8]
Unsorted list: [8, 4, 3]
bin[2]: [8]
Unsorted list: [4, 3]
bin[3]: [4]
Unsorted list: [3]
bin[4]: [3]
lowBin: 0: 1
lowBin: 0: 3
lowBin: 0: 3
lowBin: 4: 3
lowBin: 1: 4
lowBin: 3: 4
lowBin: 1: 7
lowBin: 1: 8
lowBin: 1: 8
lowBin: 0: 9
lowBin: 0: 9
sorted:[1, 3, 3, 3, 4, 4, 7, 8, 8, 9, 9]