Skip to content

Commit 0566faa

Browse files
shaontyshaonty
authored andcommitted
updated
1 parent 0cbf7ce commit 0566faa

File tree

1 file changed

+7
-7
lines changed

1 file changed

+7
-7
lines changed

Data Structure/Heap/heap.py

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
class MaxHeap(object):
55

66
def __init__(self, maxSize=None):
7-
self.heap = [float("inf")] # heap starting from index 1
7+
self.heap = []
88
self.HEAP_SIZE = maxSize
99

1010
def _swap(self,i,j):
@@ -22,7 +22,7 @@ def insert(self, item):
2222
self._bubbleUp(len(self.heap)-1)
2323

2424
def _bubbleUp(self, currentPosition):
25-
if currentPosition >= 2: # no need to do bubbleUp for 1 element
25+
if currentPosition >= 1: # no need to do bubbleUp for 1 element
2626
index = currentPosition
2727
parrentIndex = index//2
2828

@@ -31,19 +31,19 @@ def _bubbleUp(self, currentPosition):
3131
self._bubbleUp(parrentIndex)
3232

3333
def peek(self):
34-
return self.heap[1] if len(self.heap) > 1 else False
34+
return self.heap[0] if self.heap else False
3535

3636
def pop(self):
3737
element = self.peek()
3838
if element:
39-
self._swap(1, len(self.heap) - 1)
39+
self._swap(0, len(self.heap) - 1)
4040
self.heap.pop()
41-
self._bubbleDown(1)
41+
self._bubbleDown(0)
4242
return element
4343

4444
def _bubbleDown(self, index):
45-
leftChildIndex = 2 * index
46-
rightChildIndex = 2 * index + 1
45+
leftChildIndex = 2 * index + 1
46+
rightChildIndex = 2 * index + 2
4747
largest = index
4848
if len(self.heap) > leftChildIndex and self.heap[largest] < self.heap[leftChildIndex]:
4949
largest = leftChildIndex

0 commit comments

Comments
 (0)