/**
 * MinHeap2 extends MinHeap by adding two new behaviors:
 *
 *    enter    Make entries at the back of the array without
 *             making any corrections
 *    heapify  Take the resulting random array and make it a
 *             valid heap
 *
 * Note that the superclass MinHeap is the implementation with
 * the root in the [1] position of the array.
 */

public class MinHeap2 extends MinHeap
{
   static final boolean TRACE = true;
/**
 *    enter    Make entries at the back of the array without
 *             making any corrections
 */
   public void enter ( JobEntry job )
   {  if ( heap == null ) // I.e., very first enqueue
         newSize (1);     // Realistically, this should be bigger
      n++;
      if ( n > size )
         newSize (size*2);
      heap[n] = job;
   }
 /**
 *    heapify  Take the resulting random array and make it a
 *             valid heap
 *
 * From mid-point back to the beginning of the array (that is,
 * from the last heap node that has children back to the root
 * of the heap), correct the heap condition downward.  This
 * means that each subheap is processed as a heap with only the
 * root node possibly out of its proper heap position.
 * Finally, the root itself is processed after its two subheaps
 * have been corrected.
*/
   void heapify ( )
   {  if (TRACE)       // Verbose version --- show progress
      {
         System.out.println ("\nInitial state:");
         display();
         for (int top = n / 2; top > 0; top--)
         {  System.out.print("\tPress ENTER to continue:  ");
            trimEoln();
            downHeap(top);
            System.out.println ("\nAdjusting from " + top +
                                " down:");
            display();
         }
         System.out.println();
      }
      else         // Non-verbose --- just DO it!
         for (int top = n / 2; top > 0; top--)
         {  downHeap(top);  }
   }

// Discard a line of text from the console.
   static void trimEoln( )
   {  try
      {  int ck;
         while ( ( ck = System.in.read() ) != '\n' )
         {  if (ck < 0) break;  }
      }
      catch (java.io.IOException e)
      {  /* let it pass */  }
   } // end trimEoln()
}
