Lecture 7: Linear-Time Sorting
比较排序(Comparison Sorting)
堆排序,合并排序都是比较排序,最坏的情况下运行时间为O(n lg n).
比较模型(Comparison Model of Computation)
input items are black boxes (ADTs)
only support comparisons (<; >;≥;≤)
time cost = # comparisons
决策树( Decision Tree)
比较排序可以被抽象视为决策树.一棵决策树是一棵满二叉树.
例子,
决策树模型(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