0
我正在嘗試編寫和優化冒泡排序,但我的代碼實際上並沒有通過列表排序。關於爲什麼它提前停止的任何建議?冒泡排序錯誤
#!/usr/bin/env python
from random import *
import time
def bubble(lst):
counter = 0
n = len(lst)
while n > 0:
temp = 0
for i in range(1, n - 1):
if lst[i] > lst[i + 1]:
lst[i], lst[i + 1] = lst[i + 1], lst[i] # swap
temp = i
counter += 1 # to compare the speed to the
# unoptimized bubble sort
n = temp
return counter
def main():
lst = range(10)
shuffle(lst)
print lst
start = time.time()
counter = bubble(lst)
print lst
end = time.time()
print counter
print "time", end - start
main()
這是家庭作業? – crashmstr
用於python中的氣泡排序的[google搜索](http://www.google.com.ph/search?q=bubble+sort+python)就足夠了:-) – OnesimusUnbound