Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
254 views
in Technique[技术] by (71.8m points)

Python : How to stop while loop while sorting list?

I am writing code to sort elements in list and I kind of achieved it but unable to stop while loop.

I want to stop while loop when all element in list are sorted.

Code:

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)

Output:

[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]........

I know there are 10s of Q&A on sorting list but I want to achieve this way only(if possible).

Can anyone help me to stop this while loop?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Perhaps a bit more efficient than chepner's, not having an extra assignment for every swap, instead just use temp to detect whether there was a change:

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...