1. 冒泡排序
def bubble_sort(li): for i in range(len(li) - 1):
for j in range(len(li) - i - 1): if li[j] > li[j+1]: li[j], li[j+1] = li[j+1], li[j]
2. 选择排序
def select_sort(li): for i in range(len(li) - 1): min_loc = i for j in range(i+1, len(li)): if li[min_loc] > li[j]: min_loc = j li[i], li[min_loc] = li[min_loc], li[i]
3. 插入排序
def insert_sort(li): for i in range(1, len(li)): temp = li[i] j = i - 1 while j >= 0 and li[j] > temp: li[j+1] = li[j] j -= 1 li[j+1] = temp
4. 快排
def partition(li, left, right): temp = li[left] while left < right: while left < right and li[right] >= temp: right -= 1 li[left] = li[right] while left < right and li[left] <= temp: left += 1 li[right] = li[left] li[left] = temp return left 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)
5. 归并排序
def merge(li, left, mid, right): i = left j = mid + 1 ltemp = [] while i <= mid and j <= right: if li[i] < li[j]: ltemp.append(li[i]) i += 1 else: ltemp.append(li[j]) j += 1 while i <= mid: ltemp.append(li[i]) i += 1 while j <= right: ltemp.append(li[j]) j += 1 li[left:right+1] = ltemp def merge_sort(li, left, right): if left < right: mid = (left + right) // 2 merge_sort(li, left, mid) merge_sort(li, mid+1, right) merge(li, left, mid, right)
6. 堆排序
def sift(li, left, right): i = left j = 2 * i + 1 temp = li[left] while j <= right: if j + 1 <= right and li[j] < li[j+1]: j = j + 1 if temp < li[j]: li[i] = li[j] i = j j = 2 * i + 1 else: break li[i] = temp def heap_sort(li): n = len(li) for i in range(n//2-1, -1, -1): sift(li, i, n-1) for i in range(n-1, -1, -1): li[0], li[i] = li[i], li[0] sift(li, 0, i-1)
大根堆:完全二叉树,节点 大于 其左右子节点
9 下标 i
5 8 2i +1 2i + 2
3 1 4 7
0 2
[9, 5, 8, 3, 1, 4, 7, 0, 2]
小根堆:完全二叉树,节点 小于 其左右子节点