Lecture 7: Linear-Time Sortingpython
比較排序(Comparison Sorting)算法
堆排序,合併排序都是比較排序,最壞的狀況下運行時間爲O(n lg n).app
比較模型(Comparison Model of Computation)spa
input items are black boxes (ADTs) code
only support comparisons (<; >;≥;≤) 排序
time cost = # comparisonsci
決策樹( Decision Tree)input
比較排序能夠被抽象視爲決策樹.一棵決策樹是一棵滿二叉樹.it
例子,io
決策樹模型(Decision Tree Model )
One tree size for each input size n
Running time of algo: length of path taken
Worst-case running time: height of the tree
定理:任何一個比較排序算法在最壞的狀況下,都須要Ω(n lg n)次的比較.
證實:
線性時間排序
若是須要排序的數據介於0~k之間的整數.
計數排序(Counting Sort)
步驟:
PYTHON 代碼:
def CountingSort_v1(A,max_k): L =[] for j in range(max_k): L.append([]) for j in range(len(A)): L[A[j]].append(A[j]) outPut =[] for j in range(max_k): outPut.extend(L[j]) return outPut
或
PYTHON 代碼:
def CountingSort_v2(A,max_k): C =[] for j in range(max_k): C.append(0) for j in range(len(A)): C[A[j]] = C[A[j]] + 1 #print("C",C) for i in range(1,max_k): C[i] = C[i] + C[i - 1] outPut =[] for j in range(len(A)): outPut.append(0) for j in range(len(A) - 1,-1,-1): outPut[C[A[j]] - 1] = A[j] C[A[j]] = C[A[j]] - 1 return outPut