快速排序,归并排序
快速排序
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 left < right and li[right] >= tmp: right -= 1 li[left] = li[right] while left < right and li[left] <= tmp: left += 1 li[right] = li[left] li[left] = tmp return left import random li = list(range(100)) random.shuffle(li) quick_sort(li, 0, len(li)-1) print(li)
归并排序
def merge(li, low, mid, high): # 列表两段有序: [low, mid] [mid+1, high] i = low j = mid + 1 li_tmp = [] while i <= mid and j <= high: if li[i] <= li[j]: li_tmp.append(li[i]) i += 1 else: li_tmp.append(li[j]) j += 1 while i <= mid: li_tmp.append(li[i]) i += 1 while j <= high: li_tmp.append(li[j]) j += 1 # li_tmp[0:high-low+1] li[low:high+1] for i in range(low, high+1): li[i] = li_tmp[i-low] # li[low:high+1] = li_tmp def _merge_sort(li, low, high): #排序li的low到high的范围 if low < high: mid = (low + high) // 2 _merge_sort(li, low, mid) _merge_sort(li, mid+1, high) # print(li[low:mid + 1], li[mid + 1:high + 1]) merge(li, low, mid, high) # print(li[low: high + 1]) li = [10, 4, 6, 3, 8, 2, 5, 7] _merge_sort(li, 0, len(li)-1) print(li)