From 794958f3003649e2af2eefab9afa120cf930f3f5 Mon Sep 17 00:00:00 2001 From: Xuefeng-Zhu Date: Wed, 13 May 2015 22:19:40 -0500 Subject: [PATCH] change the return value of parent for root --- heaps/maxheap.py | 2 +- heaps/minheap.py | 8 ++++---- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/heaps/maxheap.py b/heaps/maxheap.py index 6f14856..f902af4 100644 --- a/heaps/maxheap.py +++ b/heaps/maxheap.py @@ -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) diff --git a/heaps/minheap.py b/heaps/minheap.py index 144e4cb..a3cce3a 100644 --- a/heaps/minheap.py +++ b/heaps/minheap.py @@ -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 @@ -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)