"""The class is incomplete, students need to provide the sift_down() function""" class MaxHeap : """ An list-based implementation of the max-heap.""" def __init__( self, max_size = 16 ): """Create a max-heap with maximum capacity of max_size.""" self._elements = [None for i in range(max_size)] self._count = 0 self._max_size = max_size def __len__( self ): """ Return the number of items in the heap.""" return self._count def __str__( self ): """Return a string representation of the heap.""" s = '' for i in range( len( self ) ): s += str( self._elements[i] ) + ', ' return s def capacity( self ): """ Return the maximum capacity of the heap.""" return len( self._elements ) def _expand(self): """double the capacity, copy the original""" temp = [None for i in range(self._max_size)] for i in range(len(self)): temp[i] = self._elements[i] self._max_size *= 2 self._elements = [None for i in range(self._max_size)] for i in range(len(temp)): self._elements[i] = temp[i] def add( self, value ): """ Add a new value to the heap.""" if self._count >= len(self): # full! double the capacity self._expand() # Add the new value to the end of the list. self._elements[ self._count ] = value self._count += 1 # Sift the new value up the tree. self._sift_up( self._count - 1 ) def extract( self ): """ Extract the maximum value from the heap.""" assert self._count > 0, "Cannot extract from an empty heap." # Save the root value and copy the last heap value to the root. value = self._elements[0] self._count -= 1 self._elements[0] = self._elements[ self._count ] # Sift the root value down the tree. self._sift_down( 0 ) return value def _sift_up( self, ndx ): """Sift the value at the ndx element up the tree.""" if ndx > 0 : parent = (ndx - 1) // 2 if self._elements[ndx] > self._elements[parent] : # swap elements self._elements[ndx], self._elements[parent] = \ self._elements[parent], self._elements[ndx] self._sift_up( parent ) def _sift_down( self, ndx ): """ Sift the value at the ndx element down the tree. """ pass