我怎样才能让这个泡泡更像Python?

2024-05-01 21:40:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下代码:

Sorted=False
while not Sorted:
    Sorted=True
    for x,y in enumerate(List[:-1]):
        if List[x]>List[x+1]:
            List[x],List[x+1]=List[x+1],List[x]
            Sorted=False

然而,使用

Sorted=True/False

重复是非常难看的,编写类似以下内容的代码会更好:

while True:
    for x,y in enumerate(List[:-1]):
        if List[x]>List[x+1]:
            List[x],List[x+1]=List[x+1],List[x]
            break
    else:break

唯一的问题是,如此早地中断循环会导致循环重复多次,从而占用更多的时间。有没有办法让代码更具python风格,或者我只需要让它保持丑陋


Tags: 代码infalsetrueforif时间not
1条回答
网友
1楼 · 发布于 2024-05-01 21:40:58
  1. 您的第二个版本不是冒泡排序

  2. 我只需要将循环更改为

      for idx in range(len(List)-1):
         if List[idx]>List[idx+1]:
             List[idx],List[idx+1] = List[idx+1],List[idx]
             Sorted=False
    

相关问题 更多 >