我不太明白这里国旗的用法,尽管已经解释过了

2024-04-20 08:00:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我不太明白这里国旗的用法,尽管已经解释过了。我自己在研究常见的算法,我有以下方法来执行冒泡排序(取自Stack滥用职权):

我把它改成:

def bubble_sort(nums):
    # We set swapped to True so the loop looks runs at least once
    for p in range(len(nums)):
        for i in range(len(nums) - 1):
            if nums[i] > nums[i + 1]:
                # Swap the elements
                nums[i], nums[i + 1] = nums[i + 1], nums[i]
                # Set the flag to True so we'll loop again

验证它是否工作

random_list_of_nums = [5, 2, 1, 8, 4]
bubble_sort(random_list_of_nums)
print(random_list_of_nums)

def bubble_sort(nums):
    # We set swapped to True so the loop looks runs at least once
    swapped = True
    while swapped:
        swapped = False
        for i in range(len(nums) - 1):
            if nums[i] > nums[i + 1]:
                # Swap the elements
                nums[i], nums[i + 1] = nums[i + 1], nums[i]
                # Set the flag to True so we'll loop again
                swapped = True

验证它是否工作

random_list_of_nums = [5, 2, 1, 8, 4]
bubble_sort(random_list_of_nums)
print(random_list_of_nums)

它应该是内部循环的,但实际上不是


Tags: ofthetoinlooptrueforso