【发布时间】:2013-09-16 16:36:54
【问题描述】:
我找不到任何有效的 Python 3.3 归并排序算法代码,所以我自己做了一个。有什么办法可以加快速度吗?它在大约 0.3-0.5 秒内对 20,000 个数字进行排序
def msort(x):
result = []
if len(x) < 2:
return x
mid = int(len(x)/2)
y = msort(x[:mid])
z = msort(x[mid:])
while (len(y) > 0) or (len(z) > 0):
if len(y) > 0 and len(z) > 0:
if y[0] > z[0]:
result.append(z[0])
z.pop(0)
else:
result.append(y[0])
y.pop(0)
elif len(z) > 0:
for i in z:
result.append(i)
z.pop(0)
else:
for i in y:
result.append(i)
y.pop(0)
return result
【问题讨论】:
-
您不应该从列表中
pop,因为这会不必要地反复移动数组元素。在迭代列表时,您应该避免更改列表。 -
另外,在合并排序的普通实现中可能没有特定于 Python 3.3 的内容,因此您只需在 Google 上搜索“python mergesort”并使用您找到的任何实现,即使它适用于旧版本。比如这个:geekviewpoint.com/python/sorting/mergesort
-
问题太老了,但它不是为结果数组使用更多内存合并排序已经使用数组的双内存对其进行排序我们再次在结果中生成数组。
标签: python python-3.x algorithm sorting mergesort