环境:Python3.8 PyCharm Community Edition 2021.2
以列表: [1,34,5,32,4,6,66,4] 为例:
nums = [1,34,5,32,4,6,66,4] for i in range(len(nums)-1): for j in range(len(nums)-i-1): if nums[j] > nums[j+1]: #若逆序,则交换 nums[j],nums[j+1] = nums[j+1],nums[j] print(nums)
打印后:
[1, 4, 4, 5, 6, 32, 34, 66]