# 兩兩相比, 將大的放到後面, 每一回合會把一個key 放到正確位置(最後方的key) defbubble_sort(nums): l = len(nums) for i inrange(l): for j inrange(i-1): if nums[i] < nums[j]: nums[i] , nums[j] = nums[j], nums[i]
# 每次當前回合最小的和最左邊未排序的數字(index: i)交換 defselection_sort(nums): for i inrange(len(nums)): pivot = i for j inrange(i+1,len(nums)): if nums[j] < nums[pivot]: pivot = j nums[i-1],nums[pivot] = nums[pivot] , nums[i-1]
# divide and conqure 技巧, 每次把串列對半切,並且串列長度<=1 時,開始 merge defmerge_sort(nums): iflen(nums) <= 1 : return nums m = len(nums)//2 l = merge_sort(nums[:m]) r = merge_sort(nums[m:]) res = [] while l and r : if l[0] < r[0]: res.append(l.pop(0)) else: res.append(r.pop(0)) res += l or r return res