冒泡排序新方式

# Start with a list of numbers that ain't sorted
numbers=[0,5,1,4,2,8]
# Keep track of whether any swaps were made on the previous i teration
# If no swaps were made, the List is already sorted and we can stop
swapped = True
while swapped:
    # Set swapped to False SO we can check if any swaps are made Later
    swapped = False
    # For each pair of adjacent elements,
    for i in range(len(numbers) - 1):
        # If the first element is greater than the second,
        if numbers[i] > numbers[i + 1]:
        # Swap the el ements
            numbers[i], numbers[i + 1] = numbers[i + 1], numbers[i]
            # Set swapped to True SO we know to keep Looping
            swapped = True
# At this point, the list is sorted
print( numbers )
posted @ 2022-12-10 11:57  ty1539  阅读(22)  评论(0编辑  收藏  举报