Advertisement
fahadkalil

max_heap_2019_2

Sep 11th, 2019
406
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.45 KB | None | 0 0
  1. class MaxHeap:
  2.     def __init__(self):
  3.         self.heap = [0]
  4.  
  5.     def put(self, item):
  6.         self.heap.append(item)
  7.         self.__floatUp(len(self.heap) - 1)
  8.  
  9.     def get(self):
  10.         if len(self.heap) > 2:
  11.             self.__swap(1, len(self.heap) - 1)
  12.             max = self.heap.pop()
  13.             self.__bubbleDown(1)
  14.         elif len(self.heap) == 2:
  15.             max = self.heap.pop()
  16.         else:
  17.             max = False
  18.         return max
  19.  
  20.     def peek(self):
  21.         if self.heap[1]:
  22.             return self.heap[1]
  23.         return False
  24.  
  25.     def __swap(self, i, j):
  26.         self.heap[i], self.heap[j] = self.heap[j], self.heap[i]
  27.  
  28.     def __floatUp(self, index):
  29.         parent = index//2
  30.         if index <= 1: # nao faz nada se for raiz
  31.             return
  32.         elif self.heap[index] > self.heap[parent]:
  33.             self.__swap(index, parent)
  34.             self.__floatUp(parent)
  35.  
  36.     def __bubbleDown(self, index):
  37.         left = index * 2
  38.         right = index * 2 + 1
  39.         maior = index
  40.         if len(self.heap) > left and self.heap[maior] < self.heap[left]:
  41.             maior = left
  42.         if len(self.heap) > right and self.heap[maior] < self.heap[right]:
  43.             maior = right
  44.  
  45.         if maior != index:
  46.             self.__swap(index, maior)
  47.             self.__bubbleDown(maior)
  48.  
  49. '''
  50. ## TESTE ##
  51. h = MaxHeap()
  52. h.put(45)
  53. h.put(55)
  54. h.put(33)
  55.  
  56. print(h.get())
  57. print(h.get())
  58. print(h.get())
  59. '''
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement