尽管已经解释了

时间:2019-09-20 03:53:29

标签: python

即使已经解释了,我在这里也不十分了解该标志的用法。我正在独自研究通用算法,下面是执行冒泡排序(摘自stackabuse)的信息:

我将其修改为:

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)

应该在内部循环,但不是

0 个答案:

没有答案