MIT Introduction to Algorithms 学习笔记(八)

 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)

比较排序可以被抽象视为决策树.一棵决策树是一棵满二叉树.

例子,

135449_ifLt_106593.jpg

135449_NvLK_106593.png

 

决策树模型(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)次的比较.

证明:

135518_CkMY_106593.png

 

线性时间排序

如果需要排序的数据介于0~k之间的整数.

 

计数排序(Counting Sort)

步骤:

135644_Ciye_106593.png

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

 

135644_qeEJ_106593.png

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

转载于:https://my.oschina.net/hyaicc/blog/598330

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值