zoukankan      html  css  js  c++  java
  • Python -堆的实现

         最小(大)堆是按完全二叉树的排序顺序的方式排布堆中元素的,并且满足:ai  >a(2i+1)  and ai>a(2i+2)( a <a(2i+1)  and ai<a(2i+2)).堆是一种高级的数据结构,在Python中,有相应的模块deapq。

    下面给出自己编写的代码实现最小堆与使用heapq模块实现最小堆作一个对比:

    #定义Myheap类

    import heapq as p
    import random 
    class MyHeap(object):
        def __init__(self,arr=[]):
            self.n=len(arr)
            self.list=arr
        def creat_heap(self):
            p.heapify(self.list) #建堆
            return self.list      
        def creat_heap1(self):
            parent_num=(self.n-1)/2
            while 0<=parent_num:
                self.siftdown(parent_num)
                parent_num-=1
            return self.list
        def siftdown(self,parent_num):
            i=parent_num
            j=2*parent_num+1
            temp=self.list[parent_num]
            while j<self.n :
                if j<self.n-1 and self.list[j+1]<self.list[j] : 
                    j=j+1
                if temp<=self.list[j]:
                    break    
                else:
                    self.list[i]=self.list[j]
                    i=j
                    j=2*i+1
            self.list[i]=temp 
        def heap_sort(self): #堆排序
            b=[]
            for i in xrange(self.n):
                 p.heapify(self.list)
                 b.append(p.heappop(self.list))
            return b
            

    测试:

    1 a1=[random.randint(1,100) for i in xrange(10)]
    2 print a1
    3 myheap1=MyHeap(a1)
    4 myheap2=MyHeap(a1)
    5 print myheap1.creat_heap()
    6 print myheap2.creat_heap1()
    7 print myheap1.heap_sort()

    结果:

    [86, 44, 34, 10, 85, 30, 62, 60, 53, 21]
    [10, 21, 30, 44, 85, 34, 62, 60, 53, 86]
    [10, 21, 30, 44, 85, 34, 62, 60, 53, 86]

  • 相关阅读:
    Asp.Net MVC<一> : 三层架构、MVC
    To IOC,代码结构演变的随想
    .net网站的文件上传读取进度条和断点下载
    NPOI导入,导出
    瀑布流,纵向
    主键、外键、索引
    java基础语法要点<二>(基于1.8)
    android 概述 及四大组件
    Android Studio
    C#查看各种变量的指针地址
  • 原文地址:https://www.cnblogs.com/whb-20160329/p/6665327.html
Copyright © 2011-2022 走看看