Advertisement
Guest User

heap.java

a guest
Mar 29th, 2013
265
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 8.73 KB | None | 0 0
  1. // heap.java
  2. // demonstrates heaps
  3. // to run this program: C>java HeapApp
  4. import java.io.*;
  5. ////////////////////////////////////////////////////////////////
  6. class Node
  7. {
  8.     private int iData;             // data item (key)
  9.     // -------------------------------------------------------------
  10.     public Node(int key)           // constructor
  11.     { iData = key; }
  12.     // -------------------------------------------------------------
  13.     public int getKey()
  14.     { return iData; }
  15.     // -------------------------------------------------------------
  16.     public void setKey(int id)
  17.     { iData = id; }
  18.     // -------------------------------------------------------------
  19. }  // end class Node
  20. ////////////////////////////////////////////////////////////////
  21. class Heap
  22. {
  23.     private Node[] heapArray;
  24.     private int maxSize;           // size of array
  25.     private int currentSize;       // number of nodes in array
  26.     // -------------------------------------------------------------
  27.     public Heap(int mx)            // constructor
  28.     {
  29.         maxSize = mx;
  30.         currentSize = 0;
  31.         heapArray = new Node[maxSize];  // create array
  32.     }
  33.     // -------------------------------------------------------------
  34.     public boolean isEmpty()
  35.     { return currentSize==0; }
  36.     // -------------------------------------------------------------
  37.     public int getCurrentSizeInc()
  38.     { return currentSize++; }
  39.     // -------------------------------------------------------------
  40.     public boolean insert(int key)
  41.     {
  42.         if(currentSize==maxSize)
  43.             return false;
  44.         Node newNode = new Node(key);
  45.         heapArray[currentSize] = newNode;
  46.         trickleUp(currentSize++);
  47.         return true;
  48.     }  // end insert()
  49.     // -------------------------------------------------------------
  50.     public boolean toss(int key)
  51.     {
  52.         if(currentSize==maxSize)
  53.             return false;
  54.         Node newNode = new Node(key);
  55.         heapArray[currentSize] = newNode;
  56.         currentSize++;
  57.         return true;
  58.     }  // end toss()
  59.     // -------------------------------------------------------------
  60.     public void trickleUp(int index)
  61.     {
  62.         int parent = (index-1) / 2;
  63.         Node bottom = heapArray[index];
  64.  
  65.         while( index > 0 &&
  66.                 heapArray[parent].getKey() < bottom.getKey() )
  67.         {
  68.             heapArray[index] = heapArray[parent];  // move it down
  69.             index = parent;
  70.             parent = (parent-1) / 2;
  71.         }  // end while
  72.         heapArray[index] = bottom;
  73.     }  // end trickleUp()
  74.     // -------------------------------------------------------------
  75.     public void restoreHeap(int index)
  76.     {
  77.         int parent = (index-1) / 2;
  78.         Node bottom = heapArray[index];
  79.  
  80.         while( index > 0 &&
  81.                 heapArray[parent].getKey() < bottom.getKey() )
  82.         {
  83.             heapArray[index] = heapArray[parent];  // move it down
  84.             index = parent;
  85.             parent = (parent-1) / 2;
  86.         }  // end while
  87.         heapArray[index] = bottom;
  88.         while(index != 0)
  89.         {
  90.             restoreHeap(parent++);
  91.         }
  92.  
  93.     }  // end restoreHeap()
  94.     // -------------------------------------------------------------
  95.     public Node remove()           // delete item with max key
  96.     {                           // (assumes non-empty list)
  97.         Node root = heapArray[0];
  98.         heapArray[0] = heapArray[--currentSize];
  99.         trickleDown(0);
  100.         return root;
  101.     }  // end remove()
  102.     // -------------------------------------------------------------
  103.     public void trickleDown(int index)
  104.     {
  105.         int largerChild;
  106.         Node top = heapArray[index];       // save root
  107.         while(index < currentSize/2)       // while node has at
  108.         {                               //    least one child,
  109.             int leftChild = 2*index+1;
  110.             int rightChild = leftChild+1;
  111.             // find larger child
  112.             if(rightChild < currentSize &&  // (rightChild exists?)
  113.                     heapArray[leftChild].getKey() <
  114.                     heapArray[rightChild].getKey())
  115.                 largerChild = rightChild;
  116.             else
  117.                 largerChild = leftChild;
  118.             // top >= largerChild?
  119.             if( top.getKey() >= heapArray[largerChild].getKey() )
  120.                 break;
  121.             // shift child up
  122.             heapArray[index] = heapArray[largerChild];
  123.             index = largerChild;            // go down
  124.         }  // end while
  125.         heapArray[index] = top;            // root to index
  126.     }  // end trickleDown()
  127.     // -------------------------------------------------------------
  128.     public boolean change(int index, int newValue)
  129.     {
  130.         if(index<0 || index>=currentSize)
  131.             return false;
  132.         int oldValue = heapArray[index].getKey(); // remember old
  133.         heapArray[index].setKey(newValue);  // change to new
  134.  
  135.         if(oldValue < newValue)             // if raised,
  136.             trickleUp(index);                // trickle it up
  137.         else                                // if lowered,
  138.             trickleDown(index);              // trickle it down
  139.         return true;
  140.     }  // end change()
  141.     // -------------------------------------------------------------
  142.     public void displayHeap()
  143.     {
  144.         System.out.print("heapArray: ");    // array format
  145.         for(int m=0; m<currentSize; m++)
  146.             if(heapArray[m] != null)
  147.                 System.out.print( heapArray[m].getKey() + " ");
  148.             else
  149.                 System.out.print( "-- ");
  150.         System.out.println();
  151.         // heap format
  152.         int nBlanks = 32;
  153.         int itemsPerRow = 1;
  154.         int column = 0;
  155.         int j = 0;                          // current item
  156.         String dots = "...............................";
  157.         System.out.println(dots+dots);      // dotted top line
  158.  
  159.         while(currentSize > 0)              // for each heap item
  160.         {
  161.             if(column == 0)                  // first item in row?
  162.                 for(int k=0; k<nBlanks; k++)  // preceding blanks
  163.                     System.out.print(' ');
  164.             // display item
  165.             System.out.print(heapArray[j].getKey());
  166.  
  167.             if(++j == currentSize)           // done?
  168.                 break;
  169.  
  170.             if(++column==itemsPerRow)        // end of row?
  171.             {
  172.                 nBlanks /= 2;                 // half the blanks
  173.                 itemsPerRow *= 2;             // twice the items
  174.                 column = 0;                   // start over on
  175.                 System.out.println();         //    new row
  176.             }
  177.             else                             // next item on row
  178.                 for(int k=0; k<nBlanks*2-2; k++)
  179.                     System.out.print(' ');     // interim blanks
  180.         }  // end for
  181.         System.out.println("\n"+dots+dots); // dotted bottom line
  182.     }  // end displayHeap()
  183.     // -------------------------------------------------------------
  184. }  // end class Heap
  185. ////////////////////////////////////////////////////////////////
  186. class HeapApp
  187. {
  188.     public static void main(String[] args) throws IOException
  189.     {
  190.         int value, value2;
  191.         Heap theHeap = new Heap(31);  // make a Heap; max size 31
  192.         boolean success;
  193.  
  194.         theHeap.insert(70);           // insert 10 items
  195.         theHeap.insert(40);
  196.         theHeap.insert(50);
  197.         theHeap.insert(20);
  198.         theHeap.insert(60);
  199.         theHeap.insert(100);
  200.         theHeap.insert(80);
  201.         theHeap.insert(30);
  202.         theHeap.insert(10);
  203.         theHeap.insert(90);
  204.  
  205.         while(true)                   // until [Ctrl]-[C]
  206.         {
  207.             System.out.print("Enter first letter of ");
  208.             System.out.print("show, insert, remove, change, toss, 'e' for restore: ");
  209.             int choice = getChar();
  210.             switch(choice)
  211.             {
  212.             case 's':                        // show
  213.                 theHeap.displayHeap();
  214.                 break;
  215.             case 'i':                        // insert
  216.                 System.out.print("Enter value to insert: ");
  217.                 value = getInt();
  218.                 success = theHeap.insert(value);
  219.                 if( !success )
  220.                     System.out.println("Can't insert; heap full");
  221.                 break;
  222.             case 'r':                        // remove
  223.                 if( !theHeap.isEmpty() )
  224.                     theHeap.remove();
  225.                 else
  226.                     System.out.println("Can't remove; heap empty");
  227.                 break;
  228.             case 'c':                        // change
  229.                 System.out.print("Enter current index of item: ");
  230.                 value = getInt();
  231.                 System.out.print("Enter new key: ");
  232.                 value2 = getInt();
  233.                 success = theHeap.change(value, value2);
  234.                 if( !success )
  235.                     System.out.println("Invalid index");
  236.                 break;
  237.             case 't':                        // insert
  238.                 System.out.print("Enter value to toss: ");
  239.                 value = getInt();
  240.                 success = theHeap.toss(value);
  241.                 if( !success )
  242.                     System.out.println("Can't toss; heap full");
  243.                 break;
  244.             case 'e':
  245.                 theHeap.restoreHeap(theHeap.getCurrentSizeInc());
  246.                 break;
  247.             default:
  248.                 System.out.println("Invalid entry\n");
  249.             }  // end switch
  250.         }  // end while
  251.     }  // end main()
  252.     //-------------------------------------------------------------
  253.     public static String getString() throws IOException
  254.     {
  255.         InputStreamReader isr = new InputStreamReader(System.in);
  256.         BufferedReader br = new BufferedReader(isr);
  257.         String s = br.readLine();
  258.         return s;
  259.     }
  260.     //-------------------------------------------------------------
  261.     public static char getChar() throws IOException
  262.     {
  263.         String s = getString();
  264.         return s.charAt(0);
  265.     }
  266.     //-------------------------------------------------------------
  267.     public static int getInt() throws IOException
  268.     {
  269.         String s = getString();
  270.         return Integer.parseInt(s);
  271.     }
  272.     //-------------------------------------------------------------
  273. }  // end class HeapApp
  274. ////////////////////////////////////////////////////////////////
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement