堆和索引堆的实现(python)

'''
索引堆
'''
'''

实现使用2个辅助数组来做.有点像dat.用哈希表来做修改不行,只是能找到这个索引,而需要change操作
还是需要自己手动写.所以只能用双数组实现.

#引入索引堆的核心就是为了改变堆里面任意一个元素的值,然后继续维护这个堆.
'''


'''下面手动写堆'''
'''做大根堆然后输出升序排列'''#感觉之前写的都不对,heapify太弱了,不能按方向调整.
#需要修改成带shift up,shift down操作的堆,最终目标实现双辅助数组的最大索引堆
class Maxheap():
    def __init__(self,capacity):#capacity是最大容量
        self.data=[0]*capacity
        self.count=0
        self.capacity=capacity
    def size(self):
        return self.count
    def empty(self):
        return self.count==0

    def shiftup(self,count):
        while count>0 and self.data[(count-1)//2]<self.data[count]:
            self.data[(count-1)//2],self.data[count]=self.data[count],self.data[(count-1)//2]
            count=(count-1)//2

    def shiftdown(self,k):#把堆的k索引的元素进行shiftdown操作,
                          #每一次这个操作都能把k位置作为head的子树给heapify了.
        while 2*k+1<=self.count-1 :
           left=2*k+1
           right=min(2*k+2,self.count-1)
           tmpindex=k
           if self.data[left]>self.data[k]:
               tmpindex=left
           if self.data[right]>self.data[tmpindex]:
               tmpindex=right
           if tmpindex==k:
               return 
           else:
               self.data[tmpindex],self.data[k]=self.data[k],self.data[tmpindex]
               k=tmpindex


        


    def insert(self,item):#建立只需要shift up
        self.data[self.count]=item
        
        self.shiftup(self.count)#把count位置的元素向上移动维护堆
        self.count+=1


    def pop(self):#弹出堆定元素
        self.data[0],self.data[self.count-1]=self.data[self.count-1],self.data[0]
        output=self.data[self.count-1]
        self.count-=1
        if self.count>0:
         self.shiftdown(0)#把索引为0的进行shiftdown操作
        return output
    def show_data(self):#因为堆,需要不动态删除,为了速度.所以不要的元素只是把它放到count-1 这个
                      #index后面而已,通过show_data来读取data中有效元素
        a=self.data[:self.count]
        return a
    def heapify(self,list1):#把数组直接建立成一个最大堆
        self.data=list1#python的列表动态的,直接赋值即可.不用管capacity
        self.capacity=len(list1)
        self.count=self.capacity
        for i in range((self.capacity-2)//2,-1,-1):
            self.shiftdown(i)
        return self.data
    def heapsort(self,list1):#直接pop 就实现了.因为前面都已经写好了
        self.heapify(list1)
        while self.count>1:
         self.pop()#弹出一个

        return self.data




#下面是测试
a=Maxheap(10)


aa=a.heapify([1,4,5,6,7,8,9,-1])
print(aa)

aaa=a.heapsort([1,4,5,6,7,8,9,-1])
print(aaa)
View Code         堆的实现

猜你喜欢

转载自www.cnblogs.com/zhangbo2008/p/9184166.html