首页 > 解决方案 > Python:排序列表时如何停止while循环?

问题描述

我正在编写代码来对列表中的元素进行排序,并且我实现了它,但无法停止 while 循环。

当列表中的所有元素都已排序时,我想停止 while 循环。

代码:

a = [27,21,22,1,11,23,0]
n=len(a)
while True:
    for i in range(n-1):
        if a[i]>a[i+1]:
            temp = a[i]
            a[i] = a[i+1]
            a[i+1] = temp
    print(a)

输出:

[21, 22, 1, 11, 23, 0, 27] [21, 1, 11, 22, 0, 23, 27] [1, 11, 21, 0, 22, 23, 27] [1, 11, 0, 21, 22, 23, 27] [1, 0, 11, 21, 22, 23, 27] [0, 1, 11, 21, 22, 23, 27] [0, 1, 11, 21, 22 , 23, 27] [0, 1, 11, 21, 22, 23, 27] [0, 1, 11, 21, 22, 23, 27].......

我知道排序列表上有 10 个问答,但我只想以这种方式实现(如果可能的话)。

谁能帮我停止这个while循环?

标签: pythonlistsortingdata-structures

解决方案


也许比 chepner 的效率高一点,每次交换都没有额外的分配,而只是temp用来检测是否有变化:

a = [27,21,22,1,11,23,0]
n = len(a)
dummy = object()
while True:
    temp = dummy
    for i in range(n-1):
        if a[i]>a[i+1]:
            temp = a[i]
            a[i] = a[i+1]
            a[i+1] = temp
    if temp is dummy:
        break
    print(a)

推荐阅读