[英]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]. 假设列表的输入是[C,B,A,exit]。
On the first "for" statement, it will swap around the list positions 0 and 1, which are C and B. 在第一个“for”语句中,它将在列表位置0和1之间交换,即C和B.
This would lead to a new list with [B, C, A] 这将导致出现[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? 但是,为什么在第二组“for”语句中,它会在A和B之间交换而不是C和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.
这可以在照片中看到,输出显示它将交换B和A.我很困惑,为什么它应该这样做时应该使用列表的位置1和2。
I have tried hand-tracing the code and I always get that C and A should have swapped instead. 我试过手动跟踪代码,我总是得到C和A应该交换。 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 . 此外,您应该永远不要将
list
用作变量名,因为它是内置类型 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.