• Python HeapSort


    __author__ = 'student'
    print 'hello world hello python'
    
    '''
    heap sort
    root  leftchild 2n+1 rightchild 2n+2
    compare them and get the maxnode
    step by step think way
    one step write the perfect program is hard
    but it is easy to write your think step by step
    build max heap
    then swap the biggest number with the size
    heap sort is a tuning for selection sort.
    '''
    la =[1,5,7,3,20,0,9,4]
    print ', '.join(str(x) for x in la)
    #from bottom to top
    def heap(la,root,heap_size=None):
        if heap_size is None:
            length=la.__len__()
        else:
            length=heap_size
        lc=root*2+1
        rc=root*2+2
        maxnode=root
        if length>lc and la[lc]>la[root]:
            maxnode=lc
        if length>rc and la[rc]>la[maxnode]:
            maxnode=rc
        if maxnode!=root:
            la[maxnode],la[root]=la[root],la[maxnode]
            heap(la,maxnode,heap_size)
    
    #build max heap
    def build_max_heap(la):
        root=la.__len__()/2-1
        while root>=0:
            heap(la,root)
            root-=1
    #heap sort
    #print ','.join (str(x) for x in xrange(la.__len__(),0,-1))
    build_max_heap(la)
    
    def heap_sort(la):
        heap_size=la.__len__()-1
        for i in xrange(heap_size,0,-1):
            la[i],la[0]=la[0],la[i] #swap
            heap(la,0,heap_size)
            heap_size-=1
            print heap_size,la
        print la
    heap_sort(la)
    
    感悟:
    学算法千万不能背,不能去抄别人的代码。
    首先要去理解整个逻辑,找一个小的数据集,自己推算出其过程,
    然后根据这个过程来写代码。
    否则抄别人的代码,被别人的思路牵着走,最后容易忘记,还得回头学。
  • 相关阅读:
    Firebird开源管理工具
    ionic3使用echarts
    ionic3安卓平台引用高德地图
    ionic3安卓版release发布
    sequelize的get/post方法例子
    sequelize查询数据的日期格式化
    sequelize的mssql配置
    cordova插件列表
    ionic3使用cordova创建自定义插件
    koa2+log4js+sequelize搭建的nodejs服务
  • 原文地址:https://www.cnblogs.com/huaxiaoyao/p/4489596.html
Copyright © 2020-2023  润新知