import java.io.*;

/**
 * MinHeap2 extends MinHeap by adding two new behaviors:
 * <pre>
 *    enter    Make entries at the back of the array without correction
 *    heapify  Take the resulting random array and make it a valid heap
 * </pre>
 * @author  Timothy Rolfe
 */

public class MinHeap2 extends MinHeap
{
   static final boolean TRACE = true;
/**
 * enter:  Make entries at the back of the array without correction
 */
   public void enter ( JobEntry job )
   {  if ( heap == null )  // I.e., very first enqueue
         newSize (1);      // Realistically, this should be greater
      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 (boolean multiPlayer)
   {  if (TRACE)       // Verbose implementation --- show progress
      {  System.out.println ("\nInitial state:");
         display();
         for (int top = n / 2; top > 0; top--)
         {  System.out.print("\t");    // tab
            if ( multiPlayer )
               HeapDrill.playerUp();   // public static method in HeapDrill
            System.out.print("Press 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 (IOException e)
      {  /* let it pass */  }
   } // end trimEoln()
} // end class MinHeap2
