1. 图解 2. 代码 from typing import List class Solution : # 冒泡排序 def bubble_sort ( self , nums : List [ int ]) - List [ int ]: n = len ( nums ) for i in range ( n ): for j in range ( 1 , n - i ): if nums [ j - 1 ] nums [ j ]: num
1. 图解
2. 代码
from typing import Listclass Solution:
# 冒泡排序
def bubble_sort(self, nums: List[int]) -> List[int]:
n = len(nums)
for i in range(n):
for j in range(1, n - i):
if nums[j - 1] > nums[j]:
nums[j - 1], nums[j] = nums[j], nums[j - 1]
return nums
# 每次用第一个和后面的作对比
def bubble_sort_2(self, nums: List[int]) -> List[int]:
n = len(nums)
for i in range(n - 1):
for j in range(i + 1, n):
if nums[i] > nums[j]:
nums[i], nums[j] = nums[j], nums[i]
return nums
if __name__ == "__main__":
s = Solution()
nums = [3,4,2,1,3,4,5,67,19]
a = s.bubble_sort(nums)
print(a)