Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class MaxHeap:
- def __init__(self):
- self.heap = [0]
- def put(self, item):
- self.heap.append(item)
- self.__floatUp(len(self.heap) - 1)
- def get(self):
- if len(self.heap) > 2:
- self.__swap(1, len(self.heap) - 1)
- max = self.heap.pop()
- self.__bubbleDown(1)
- elif len(self.heap) == 2:
- max = self.heap.pop()
- else:
- max = False
- return max
- def peek(self):
- if self.heap[1]:
- return self.heap[1]
- return False
- def __swap(self, i, j):
- self.heap[i], self.heap[j] = self.heap[j], self.heap[i]
- def __floatUp(self, index):
- parent = index//2
- if index <= 1: # nao faz nada se for raiz
- return
- elif self.heap[index] > self.heap[parent]:
- self.__swap(index, parent)
- self.__floatUp(parent)
- def __bubbleDown(self, index):
- left = index * 2
- right = index * 2 + 1
- maior = index
- if len(self.heap) > left and self.heap[maior] < self.heap[left]:
- maior = left
- if len(self.heap) > right and self.heap[maior] < self.heap[right]:
- maior = right
- if maior != index:
- self.__swap(index, maior)
- self.__bubbleDown(maior)
- '''
- ## TESTE ##
- h = MaxHeap()
- h.put(45)
- h.put(55)
- h.put(33)
- print(h.get())
- print(h.get())
- print(h.get())
- '''
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement