zoukankan      html  css  js  c++  java
  • 堆排序

    import random
    
    def generate_big_root_heap(li,low,hight):
        i = low
        j = 2 * i + 1
        tmp = li[i]
        while j <= hight:
            if j + 1 <= hight and li[j+1] > li[j]:
                j = j + 1
            if li[j] > tmp:
                li[i] = li[j]
                i = j
                j = 2 * i + 1
            else:
                break
        li[i] = tmp
    
    def generate_low_root_heap(li,low,hight):
        i = low
        j = 2 * i + 1
        tmp = li[low]
        while j <= hight:
            if j + 1 <= hight and li[j+1] < li[j]:
                j = j + 1
            if li[j] < tmp:
                li[i] = li[j]
                i = j
                j = 2 * i + 1
            else:
                break
        li[i] = tmp
    
    def heap_sort(li):
        n = len(li)
        # 建堆
        for i in range((n-1-1)//2,-1,-1):
            # generate_big_root_heap(li,i,n-1)    # 大根堆
            generate_low_root_heap(li,i,n-1)    # 小根堆
        print(li)
        # 堆向下调整
        for i in range(n-1,-1,-1):
            li[i], li[0] = li[0], li[i]
            # generate_big_root_heap(li,0,i-1)    # 大根堆
            generate_low_root_heap(li,0,i-1)    # 小根堆
    
    
    def main():
        li = [i for i in range(100)]
        random.shuffle(li)
        print(li)
        heap_sort(li)
        print(li)
    
    if __name__ == '__main__':
        main()
    

      

  • 相关阅读:
    时间,关机重启及网络常识
    bash xshell 特性
    Http介绍
    rsync 守护进程模式小记
    定时任务+邮件发送 小记
    4.iptables的匹配条件(一)
    3.iptables规则管理
    2.iptables规则查询
    1.iptables概念
    4.LVS实验构建
  • 原文地址:https://www.cnblogs.com/navysummer/p/15580698.html
Copyright © 2011-2022 走看看