Friday, June 12, 2015

Exercise 6.2-2

6.2-2 Starting with the procedure MAX-HEAPIFY, write pseudocode for the procedure MIN-HEAPIFY(A, i), which performs the corresponding manipulation on a minheap. How does the running time of MIN-HEAPIFY compare to that of MAXHEAPIFY?

Answer 


The running time is the same we just need to find the smallest instead of the greatest.

Code in C++ (code is taken from a heap implementation I made, so A is not a parameter):


void Heap :: minHeapiFy ( unsigned index )
{
   
unsigned child = getLeft ( index ) ;

   
if ( child >= getHeapSize ( ) )
       
return ;

   
if ( child < getHeapSize ( ) - 1 && heapArray [ child ] > heapArray [ child + 1 ] )
       
++ child ;

   
if ( heapArray [ index ] > heapArray [ child ] )
   
{
        swap
( heapArray [ child ] , heapArray [ index ] ) ;
        minHeapiFy
( child ) ;
   
}
}

No comments:

Post a Comment