# -*- coding: UTF-8 -*- # 遞歸實現, 把過程打印出來便於理解 def quick_sort1(lis, start, end): if start >= end: return lf = start rg = end base = lis[lf] while lf < rg: while lf < rg and lis[rg] <= base: rg -= 1 lis[lf] = lis[rg] print("while1", lis) while lf < rg and lis[lf] > base: lf += 1 lis[rg] = lis[lf] print("while2", lis) lis[lf] = base print(lis) quick_sort1(lis, rg+1, end) quick_sort1(lis, start, lf - 1) def quick_sort2(array, l, r): if l < r: q = partition(array, l, r) quick_sort2(array, l, q - 1) quick_sort2(array, q + 1, r) def partition(array, l, r): x = array[r] i = l - 1 for j in range(l, r): if array[j] <= x: i += 1 array[i], array[j] = array[j], array[i] array[i + 1], array[r] = array[r], array[i + 1] return i + 1 # 迭代替代遞歸,使用棧實現 def quick_sort3(array, l, r): if l >= r: return stack = [] stack.append(l) stack.append(r) while stack: low = stack.pop(0) high = stack.pop(0) if high - low <= 0: continue x = array[high] i = low - 1 for j in range(low, high): if array[j] <= x: i += 1 array[i], array[j] = array[j], array[i] array[i + 1], array[high] = array[high], array[i + 1] stack.extend([low, i, i + 2, high]) if __name__ == "__main__": # lis1 = [6, 4, 3, 5, 2, 1, 7, 8, 9] lis = [6, 3, 5, 2, 1, 7, 8, 9, 4] print("start....") quick_sort3(lis, 0, len(lis)-1) print(lis) print("end...")