Skip to content

Commit

Permalink
change the return value of parent for root
Browse files Browse the repository at this point in the history
  • Loading branch information
Xuefeng-Zhu committed May 14, 2015
1 parent ccb9099 commit 794958f
Show file tree
Hide file tree
Showing 2 changed files with 5 additions and 5 deletions.
2 changes: 1 addition & 1 deletion heaps/maxheap.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ def heappush(self, x):
i = len(self.heap)
self.heap.append(x)
parent = self.parent(i)
while parent != [] and self.heap[i] > self.heap[parent]:
while parent != -1 and self.heap[i] > self.heap[parent]:
self.heap[i], self.heap[parent] = self.heap[parent], self.heap[i]
i = parent
parent = self.parent(i)
8 changes: 4 additions & 4 deletions heaps/minheap.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ def is_leaf(self, i):

def parent(self, i):
if i == 0:
return []
return -1
elif i % 2 != 0: # odd
return (i - 1) / 2
return (i - 2) / 2
Expand All @@ -54,16 +54,16 @@ def build_heap(self, elem):
""" transforms a list of elements into a heap
in linear time """
self.heap = elem[:]
last_leaf = int(math.ceil( (len(self.heap)- 2) / 2))
last_leaf = self.parent(len(self.heap))
for i in range(last_leaf, -1, -1):
self.heapify(i)
self.heapify(i)

def heappush(self, x):
""" Adds a new item x in the heap"""
i = len(self.heap)
self.heap.append(x)
parent = self.parent(i)
while parent != [] and self.heap[i] < self.heap[parent]:
while parent != -1 and self.heap[i] < self.heap[parent]:
self.heap[i], self.heap[parent] = self.heap[parent], self.heap[i]
i = parent
parent = self.parent(i)
Expand Down

0 comments on commit 794958f

Please sign in to comment.