因此,我正在学习Bubble Sort,并看到了以下代码:
def bubblesort(list_a):
indexing_length = len(list_a) - 1
sorted = False
while not sorted:
sorted = True
for i in range(0, indexing_length):
if list_a[i] > list_a[i+1]:
sorted = False
list_a[i], list_a[i+1] = list_a[i+1], list_a[i] # flip position
return list_a
我尝试在笔记本上运行此代码,以便更好地理解这一点。我尝试了5、2、3、7、10、1、8,过程是这样的:
--> 2, 5, 3, 7, 10, 1, 8
--> 2, 3, 5, 7, 10, 1, 8
--> 2, 3, 5, 7, 1, 10, 8
--> 2, 3, 5, 7, 1, 8, 10
我最终选择了未排序的数组,因为我认为for循环只会执行一次迭代。我理解不对吗?有人可以向我解释一下吗?
The list will be
[2, 3, 5, 7, 1, 8, 10]
after thefor
loop completes the first time, but the value ofsorted
will be False. Since you're still inside thewhile not sorted
loop, everything inside that loop will run again, including anotherfor
loop starting at index 0.This will keep going until the list is sorted when the
for
loop completes, since that will make thewhile
loop's condition False.