简体   繁体   中英

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

Okay so this is my code that worked fine, however if I change the length variable to

length = len(bad_list)

then I get an error saying the list index is out of range, why?

I apologize if I am being really stupid, but I appreciate the help.

Thanks

You get the error because you have:

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

if i is len(lst) (The last time through the for loop), then i+1 is outside the range of the list.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM