最佳答案
一些美国广播公司最初有这样的排序算法:
for i from 0 to n-1:
for j from 0 to n-1:
if A[j] > A[i]:
swap A[i] and A[j]
Note that both i
and j
go the full range and thus j
can be both larger and smaller than i
, so it can make pairs both correct and wrong order (and it actually 是的 do both!). I thought that's a mistake (and the author later called it that) and that this would jumble the array, but it does appear to sort correctly. It's not obvious why, though. But the 密码 simplicity (going full ranges, and no +1
as in bubble sort) makes it interesting.
它是正确的吗? 如果是的话,它为什么工作? 它有名字吗?
通过测试实现 Python:
from random import shuffle
for _ in range(3):
n = 20
A = list(range(n))
shuffle(A)
print('before:', A)
for i in range(n):
for j in range(n):
if A[j] > A[i]:
A[i], A[j] = A[j], A[i]
print('after: ', A, '\n')
样本输出(上网试试!) :
before: [9, 14, 8, 12, 16, 19, 2, 1, 10, 11, 18, 4, 15, 3, 6, 17, 7, 0, 5, 13]
after: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
before: [5, 1, 18, 10, 19, 14, 17, 7, 12, 16, 2, 0, 6, 8, 9, 11, 4, 3, 15, 13]
after: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
before: [11, 15, 7, 14, 0, 2, 9, 4, 13, 17, 8, 10, 1, 12, 6, 16, 18, 3, 5, 19]
after: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
编辑: 有人指出了一个非常好的全新的 纸张关于这个算法。澄清一下,我们没有关系,这只是个巧合。据我所知,正是 提交对 arXiv 在的回答引发了我的问题,也正是 已发表对 arXiv < em > 在 之后的回答引发了我的问题。