/*
 $Header: /home/cs/guest/javagrp/netdesign/general/RCS/Heap.java,v 1.1 1996/05/21 19:14:12 hma Exp $
 */
/*
 $Log: Heap.java,v $
# Revision 1.1  1996/05/21  19:14:12  hma
# Initial revision
#
 */

//////////////////////////////////
package general;

//********************************
// the root holds the smallest element
public class Heap {
  private Vector a; // elements start from index 1, not 0 
  Object tmp;

//********************************
  public int parent( int i ) {
    return (i/2);
  }
  public int left( int i ) {
    return 2*i;
  }
  public int right( int i ) {
    return 2*i+1;
  }

//********************************
  private void heapify( int i ) {
    int l = left(i);
    int r = right(i);

    // because index counted from 1 up, here, use l < a.size() instead of l <= a.size()
    int smallest =  (l < a.size() && 
		    ((Ordered)a.elementAt(l)).getValue() < 
		    ((Ordered)a.elementAt(i)).getValue() ) ? l : i;
    // here also, r < a.size() instead of r <= a.size()
    if ( r < a.size() && ((Ordered)a.elementAt(r)).getValue() <
	((Ordered)a.elementAt(largest)).getValue() )
      smallest = r;
    if ( smallest <> i ) {
      tmp = a.elementAt(i);
      a.setElementAt(a.elementAt(smallest), i);
      a.setElementAt(tmp, smallest);
      heapify(smallest);
    }
  }
//********************************
  public Heap(Vector v) {
    a = (Vector)v.clone();
    for (int i = (a.size()-1)/2; i >= 1; i--)
      heapify(i);
  }

  public Heap(Object[] o) {
    a = new Vector();
    int i;
    for (i = 0; i < o.length; i++)
      a.addElement(o[i]);
    for (i = (a.size()-1)/2; i >= 1; i--)
      heapify(i);
  }
     
  public Object extractMin() {
    if (a.size() < 2) {
      System.err.println("heap underflow");
      System.exit(1);
    }
    Object min = a.elementAt(1);
    a.setElementAt(a.lastElement(), 1);
    a.removeElementAt(a.size()-1);
    heapify(1);
    return min;
  }

  public insert(Object key)
      
      

    
