@@ -41,29 +41,47 @@ def _parent(self, index):
4141 def _is_root (self , index ):
4242 return index == 0
4343
44+ def _swap (self , i1 , i2 ):
45+ self .data [i1 ], self .data [i2 ] = self .data [i2 ], self .data [i1 ]
46+
4447 def build_heap (self , initial_data ):
4548 for i in initial_data :
4649 self .data .append (i )
4750
4851 def heap_up (self , index ):
49- # Return if we are at the root
52+ # If we are at the root, return - we are done
5053 if self ._is_root (index ):
5154 return
5255
53- # Else, compare the current node with the parent node, and:
54- # * this node > parent node (for max heap)
55- # * this node < parent node (for min heap)
56- # Then swap and recursively do the same, but at the parent index (which is now
57- # where the node in question resides).
56+ # Else, compare the current node with the parent node, and if this node should be higher
57+ # then the parent node, then swap and recursively call on the parent index
5858 parent_index = self ._parent (index )
5959 if self .comparator (self .data [index ], self .data [parent_index ]):
60- self .data [ index ], self . data [ parent_index ] = self . data [ parent_index ], self . data [ index ]
60+ self ._swap ( index , parent_index )
6161 self .heap_up (parent_index )
62- else :
63- return
6462
6563 def heap_down (self , index ):
66- pass
64+ left_index = self ._left_child (index )
65+ right_index = self ._right_child (index )
66+ left = self .data [left_index ]
67+ right = self .data [right_index ]
68+
69+ # Find the largest child
70+ largest_child = left
71+ largest_child_index = left_index
72+ if left is not None and right is not None :
73+ if self .comparator (right , left ):
74+ largest_child = right
75+ largest_child_index = right_index
76+ elif right is not None :
77+ largest_child = right
78+ largest_child_index = right_index
79+
80+ # If the largest child is not None and is higher priority than the current, then swap
81+ # and recursively call on on the child index
82+ if largest_child is not None and self .comparator (largest_child , self .data [index ]):
83+ self ._swap (index , largest_child_index )
84+ self .heap_down (largest_child_index )
6785
6886 def push (self , item ):
6987 insert_index = self .size # Insert at the end
@@ -78,13 +96,19 @@ def peek(self):
7896 return self .data [0 ]
7997
8098 def pop (self ):
99+ if len (self .data ) < 1 or self .data [0 ] is None :
100+ return None
101+
81102 # Take item from the root
82103 item = self .data [0 ]
83104
84105 # Move the bottom-most, right-most item to the root
85- self .data [0 ] = self .data [self .size ]
86- del self .data [self .size ]
106+ self .data [0 ] = self .data [self .size - 1 ]
107+ self .data [self .size - 1 ] = None
87108 self .size -= 1
109+
110+ self .heap_down (0 )
111+
88112 return item
89113
90114 def __repr__ (self ):
0 commit comments