我有以下代码:
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风格,或者我只需要让它保持丑陋
您的第二个版本不是冒泡排序
我只需要将循环更改为
相关问题 更多 >
编程相关推荐