所以,我正在学习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循环只会执行一次迭代。我理解不对吗?有人可以向我解释一下吗?
[2, 3, 5, 7, 1, 8, 10]
循环第一次完成后,列表将为for
,但是sorted
的值为False。由于您仍在while not sorted
循环内,因此该循环内的所有内容都会再次运行,包括另一个从索引0开始的for
循环。[将继续进行直到for
循环完成后对列表进行排序,因为这会使while
循环的条件为False。
气泡排序