1- from math import floor
2-
31def heapsort (arr ):
42 pass
53
64class Heap :
75 def __init__ (self ):
8- self .storage = []
6+ self .storage = [0 ]
7+ self .size = 0
98
109 def insert (self , value ):
1110 self .storage .append (value )
12- self ._bubble_up (len (self .storage ) - 1 )
11+ self .size += 1
12+ self ._bubble_up (self .size )
1313
1414 def delete (self ):
15- if not len (self .storage ):
16- return None
17- if len (self .storage ) == 1 :
18- return self .storage .pop ()
19- max_value = self .storage [0 ]
20- self .storage [0 ] = self .storage .pop ()
21- self ._sift_down (0 )
22- return max_value
15+ retval = self .storage [1 ]
16+ self .storage [1 ] = self .storage [self .size ]
17+ self .size -= 1
18+ self .storage .pop ()
19+ self ._sift_down (1 )
20+ return retval
2321
2422 def get_max (self ):
25- return self .storage [0 ]
23+ return self .storage [1 ]
2624
2725 def get_size (self ):
28- return len ( self .storage )
26+ return self .size
2927
3028 def _bubble_up (self , index ):
31- parent_index = floor (( index - 1 ) / 2 ) if index > 0 else 0
32- if self .storage [parent_index ] < self .storage [index ]:
33- self .storage [parent_index ], self .storage [index ] = self .storage [index ], self .storage [parent_index ]
34- self . _bubble_up ( parent_index )
29+ while index // 2 > 0 :
30+ if self .storage [index // 2 ] < self .storage [index ]:
31+ self .storage [index ], self .storage [index // 2 ] = self .storage [index // 2 ], self .storage [index ]
32+ index = index // 2
3533
3634 def _sift_down (self , index ):
37- left_index = index * 2 + 1
38- right_index = index * 2 + 2
39- max_child_index = len (self .storage ) - 1
40-
41- try :
42- left_child = self .storage [left_index ]
43- except IndexError :
44- left_child = None
45-
46- try :
47- right_child = self .storage [right_index ]
48- except IndexError :
49- right_child = None
50-
51- if left_child and right_child :
52- max_child_index = left_index if left_child > right_child else right_index
53- elif left_child :
54- max_child_index = left_index
55- elif right_child :
56- max_child_index = right_child
57-
58- if self .storage [index ] < self .storage [max_child_index ]:
59- self .storage [max_child_index ], self .storage [index ] = self .storage [index ], self .storage [max_child_index ]
60- self ._sift_down (max_child_index )
35+ while (index * 2 ) <= self .size :
36+ mc = self ._max_child (index )
37+ if self .storage [index ] < self .storage [mc ]:
38+ self .storage [index ], self .storage [mc ] = self .storage [mc ], self .storage [index ]
39+ index = mc
40+
41+ def _max_child (self , index ):
42+ if index * 2 + 1 > self .size :
43+ return index * 2
44+ else :
45+ return index * 2 if self .storage [index * 2 ] > self .storage [index * 2 + 1 ] else index * 2 + 1
0 commit comments