冒泡排序: 左右比較互換 def select_sort(li): lg=len(li)-1 for i in range(lg): flag = False for j in range(lg): if li[j] > li[j+1]: li[j+1],li[j] = li[j],li[j+1] flag = True if not flag: return select_sort(li) print(li) 選擇排序 每次循環取最左邊的爲最小值去比較 def select_sort(li): lg = len(li)-1 for i in range(lg): emp = i for j in range(i+1,lg+1): if li[j] <= li[emp]: emp = j if emp != i: li[i],li[emp] = li[emp],li[i] select_sort(li) print(li) 插入排序 原始列表裏分爲有序和無序,每次從無序區裏拿一個元素插入到有序區裏 def select_sort(li): lg = len(li)-1 for i in range(1,lg): tmp = li[i] j = i-1 while j>= 0 and tmp<li[j]: li[j+1] = li[j] j = j-1 li[j+1] = tmp select_sort(li) print(li) 快排 取一個元素p,使其歸位,左邊的比起小,最右邊的比其大,遞歸完成排序 def quick_sort(li,left,right): if left<right: mid = partition(li,left,right) quick_sort(li,left,mid-1) quick_sort(li,mid+1,right) def partition(li,left,right): tmp = li[left] while left<right: while li[right] >= tmp and left<right: right -= 1 li[left] = li[right] while li[left] <= tmp and left<right: left+= 1 li[right] = li[left] li[left] = tmp return left quick_sort(li,0,len(li)-1) print(li) 歸併排序 先分組爲有序的單個列表,在合併(依賴另一個列表實現),與中間的索引比較 def merget_sort(li,left,right): if left < right: mid = (left+right) // 2 merget_sort(li,left,mid) merget_sort(li,mid+1,right) merget(li,left,mid,right) def merget(li,left,mid,right): i = left j = mid+1 ltmp = [] while i <= mid and j <= right: if li[i] <= li[j]: ltmp.append(li[i]) i+=1 else: ltmp.append(li[j]) j += 1 # 右邊沒值了 while i <= mid: ltmp.append(li[i]) i+=1 # 左邊沒值 了 while j<= right: ltmp.append(li[j]) j+=1 # 從新賦值給列表 li[left:right+1] = ltmp merget_sort(li,0,len(li)-1) print(li)
計數排序 很妙,去其索引給另外的列表,在取出來給自身
def count_sort(li,max_num):
count = [0 for i in range(max_num+1)]
for num in li:
count[num] += 1
i = 0
for num, m in enumerate(count):
for j in range(m):
li[i] = num
i += 1
count_sort(li,max(li))
print(li)