這是我在python中的排序,我似乎無法找到問題。泡沫排序不工作
我正在尋找開始創建更復雜的排序算法,但我必須先了解爲什麼我的氣泡排序不起作用。
斷言插入程序崩潰,如果不正確地排序它(這已經發生每次我都運行時間(含調試)
N=5000
#function to sort a list
def bubble_sort(numbers):
to_go = len(list_n)
while to_go != 0:
newn = 0
for i in range(1, to_go):
if list_n[i-1] > list_n[i]:
swap(i-1, i)
newn = i
to_go = newn
def swap(item_1, item_2):
list_n[item_1], list_n[item_2] = list_n[item_2], list_n[item_1]
list_n = []
for e in range(0,N):
list_n.append(random.randint(1,N-1))
copy = list_n[:]
#time the sorting routine
t1 = time.clock()
bubble_sort(copy)
t2 = time.clock()
#make sure the list was sorted correctly
list_n.sort()
assert(list_n==copy)
#print how long the function took to do the sort
print 'mySort took', t2-t1, 'seconds.'
你可能是想用'.sort()'排序拷貝,而不是排序'list_n'兩次 – mensi