气泡排序不工作

2024-09-22 16:25:31 发布

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

这是我在python中的冒泡排序,我似乎找不到问题。在

我希望开始创建更复杂的排序算法,但我必须首先了解为什么我的冒泡排序不起作用。在

如果程序没有正确排序(每次运行它(包括调试)时都会发生这种情况),插入assert会使程序崩溃

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.'

Tags: theto程序gotime排序deffunction
1条回答
网友
1楼 · 发布于 2024-09-22 16:25:31

问题基本上是将排序为numbers的列表传递给bubble_sort函数,但在函数内部,您永远不会使用该参数。在

您应该将list_n中出现的所有list_n替换为bubble_sort中的numbers,并将其作为附加参数传递给swap函数,以便实际交换正在处理的列表中的数字,而不是全局变量list_n。在

相关问题 更多 >