From 36e9a572d2ff35ddfbbb7e318f0ed5c779dbae0f Mon Sep 17 00:00:00 2001 From: Amirsoroush Date: Sat, 13 May 2023 21:31:13 +0300 Subject: [PATCH 1/2] Chapter07 - short circuiting sink and arrange method in min-heap --- Chapter07/heap.py | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/Chapter07/heap.py b/Chapter07/heap.py index ee0aa33..f6c8f3c 100644 --- a/Chapter07/heap.py +++ b/Chapter07/heap.py @@ -5,8 +5,9 @@ def __init__(self): def arrange(self, k): while k // 2 > 0: - if self.heap[k] < self.heap[k//2]: - self.heap[k], self.heap[k//2] = self.heap[k//2], self.heap[k] + if self.heap[k] > self.heap[k//2]: + break + self.heap[k], self.heap[k//2] = self.heap[k//2], self.heap[k] k //= 2 def insert(self, item): @@ -17,8 +18,9 @@ def insert(self, item): def sink(self, k): while k * 2 <= self.size: mc = self.minchild(k) - if self.heap[k] > self.heap[mc]: - self.heap[k], self.heap[mc] = self.heap[mc], self.heap[k] + if self.heap[k] < self.heap[mc]: + break + self.heap[k], self.heap[mc] = self.heap[mc], self.heap[k] k = mc def minchild(self, k): From 86fbfbcab3e3b55b18156d6d868352414e83ed7c Mon Sep 17 00:00:00 2001 From: Amirsoroush Date: Sun, 14 May 2023 01:40:52 +0300 Subject: [PATCH 2/2] Chapter07 - delete_at_location method need to check the node's parent --- Chapter07/heap.py | 1 + 1 file changed, 1 insertion(+) diff --git a/Chapter07/heap.py b/Chapter07/heap.py index f6c8f3c..c948f6c 100644 --- a/Chapter07/heap.py +++ b/Chapter07/heap.py @@ -45,6 +45,7 @@ def delete_at_location(self, location): self.heap[location] = self.heap[self.size] self.size -= 1 self.heap.pop() + self.arrange(location) self.sink(location) return item