我正在尝试在 Python 中实现冒泡排序算法,但无法理解为什么它在一种情况下有效,而在另一种情况下无效

I'm trying to implement the bubblesort algorithm in Python and can't understand why it works in one case and not another

my_list = [1,33,2,3,11,7,9,7,8]

def bubble(bad_list):
    sorted = False
    length = len(bad_list)-1

    while not sorted:
        sorted = True
        for i in range(length):
            if bad_list[i] > bad_list[i+1]:
                sorted = False
                bad_list[i], bad_list[i+1] = bad_list[i+1], bad_list[i]

    return bad_list

bubble(my_list)
print my_list

好的,我的代码运行良好,但是如果我将长度变量更改为

length = len(bad_list)

然后我收到一条错误消息,提示列表索引超出范围,为什么?

如果我真的很愚蠢,我深表歉意,但我感谢您的帮助。

谢谢

你得到这个错误是因为你有:

if bad_list[i] > bad_list[i+1]:
    ...

如果ilen(lst)(最后一次通过for循环),则i+1在列表范围之外。