冒泡排序可视化
1 普通冒泡排序
代码
def BubbleSort(nums):
for i in range(0,len(nums)):
for j in range(0, len(nums)-1-i):
if nums[j] > nums[j+1]:
nums[j], nums[j+1] = nums[j+1], nums[j]
if __name__ == '__main__':
nums = [5,4,3,2,1]
BubbleSort(nums)
print(nums)
结果
2 优化冒泡排序
代码
def BubbleSort(nums):
for i in range(0,len(nums)):
flag = False
for j in range(0, len(nums)-1-i):
if nums[j] > nums[j+1]:
nums[j], nums[j+1] = nums[j+1], nums[j]
flag = True
if flag is False:
break
if __name__ == '__main__':
nums = [1,2,3,5,4]
BubbleSort(nums)
print(nums)
结果