简体   繁体   中英

Understanding Bubble Sort in Python

I'm really confused about how this code works.

Suppose the Inputs for the list are [ C, B, A, exit].

On the first "for" statement, it will swap around the list positions 0 and 1, which are C and B.

This would lead to a new list with [B, C, A]

However, why is it that on the second set of "for" statements, it would swap around A and B instead of C and A? This can be seen in the photo where the output says that it will swap B and A. I'm so confused as to why it would do that when it should be using positions 1 and 2 of the list instead.

I have tried hand-tracing the code and I always get that C and A should have swapped instead. Can someone help explain it to me? Thank you very much in advance

def bubble(alist):
    count = 0
    count2 = 0
    for length in range(len(list)):
        for i in range(len(list) - 1):
            if list[i] > list[i + 1]:
                print("Swapping", list[i + 1], list[length])
                tmp = list[length]
                list[length] = list[i+1]
                list[i + 1] = tmp

list = []
while True:
   val = input()
   if val == "exit":
      break
   list.append(val)

counts = bubble(list)
print(list)

Picture of the output 输出图片

Your comparison

if list[i] > list[i + 1]:

does not match your swap code

tmp = list[length]
list[length] = list[i+1]
list[i + 1] = tmp

Either change you comparison to

if list[i + 1] > list[length]

or change your swap code to

tmp = list[i + 1]
list[i + 1] = list[i]
list[i] = tmp

Also, you should really never use list as a variable name as it is a built-in type .

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