Demonstrates heaps : Heaps « Collections Data Structure « Java

Home
Java
1.2D Graphics GUI
2.3D
3.Advanced Graphics
4.Ant
5.Apache Common
6.Chart
7.Class
8.Collections Data Structure
9.Data Type
10.Database SQL JDBC
11.Design Pattern
12.Development Class
13.EJB3
14.Email
15.Event
16.File Input Output
17.Game
18.Generics
19.GWT
20.Hibernate
21.I18N
22.J2EE
23.J2ME
24.JavaFX
25.JDK 6
26.JDK 7
27.JNDI LDAP
28.JPA
29.JSP
30.JSTL
31.Language Basics
32.Network Protocol
33.PDF RTF
34.Reflection
35.Regular Expressions
36.Scripting
37.Security
38.Servlets
39.Spring
40.Swing Components
41.Swing JFC
42.SWT JFace Eclipse
43.Threads
44.Tiny Application
45.Velocity
46.Web Services SOA
47.XML
Java » Collections Data Structure » Heaps 




Demonstrates heaps
Demonstrates heaps
   
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;


public class Heap {
  private Node[] heapArray;

  private int maxSize; // size of array

  private int currentSize; // number of nodes in array

  public Heap(int mx) {
    maxSize = mx;
    currentSize = 0;
    heapArray = new Node[maxSize]// create array
  }

  public boolean isEmpty() {
    return currentSize == 0;
  }

  public boolean insert(int key) {
    if (currentSize == maxSize)
      return false;
    Node newNode = new Node(key);
    heapArray[currentSize= newNode;
    trickleUp(currentSize++);
    return true;
  

  public void trickleUp(int index) {
    int parent = (index - 12;
    Node bottom = heapArray[index];

    while (index > && heapArray[parent].getKey() < bottom.getKey()) {
      heapArray[index= heapArray[parent]// move it down
      index = parent;
      parent = (parent - 12;
    }
    heapArray[index= bottom;
  }

  public Node remove() // delete item with max key
  // (assumes non-empty list)
    Node root = heapArray[0];
    heapArray[0= heapArray[--currentSize];
    trickleDown(0);
    return root;
  // end remove()

  public void trickleDown(int index) {
    int largerChild;
    Node top = heapArray[index]// save root
    while (index < currentSize / 2// while node has at
    //    least one child,
      int leftChild = * index + 1;
      int rightChild = leftChild + 1;
      // find larger child
      if (rightChild < currentSize
          && // (rightChild exists?)
          heapArray[leftChild].getKey() < heapArray[rightChild]
              .getKey())
        largerChild = rightChild;
      else
        largerChild = leftChild;
      // top >= largerChild?
      if (top.getKey() >= heapArray[largerChild].getKey())
        break;
      // shift child up
      heapArray[index= heapArray[largerChild];
      index = largerChild; // go down
    }
    heapArray[index= top; // root to index
  }

  public boolean change(int index, int newValue) {
    if (index < || index >= currentSize)
      return false;
    int oldValue = heapArray[index].getKey()// remember old
    heapArray[index].setKey(newValue)// change to new

    if (oldValue < newValue
      trickleUp(index)
    else
      trickleDown(index);
    return true;
  }

  public void displayHeap() {
    System.out.print("heapArray: ")// array format
    for (int m = 0; m < currentSize; m++)
      if (heapArray[m!= null)
        System.out.print(heapArray[m].getKey() " ");
      else
        System.out.print("-- ");
    int nBlanks = 32;
    int itemsPerRow = 1;
    int column = 0;
    int j = 0// current item

    while (currentSize > 0// for each heap item
    {
      if (column == 0// first item in row?
        for (int k = 0; k < nBlanks; k++)
          // preceding blanks
          System.out.print(' ');
      // display item
      System.out.print(heapArray[j].getKey());

      if (++j == currentSize// done?
        break;

      if (++column == itemsPerRow// end of row?
      {
        nBlanks /= 2// half the blanks
        itemsPerRow *= 2// twice the items
        column = 0// start over on
        System.out.println()//    new row
      else
        // next item on row
        for (int k = 0; k < nBlanks * 2; k++)
          System.out.print(' ')// interim blanks
    
  }

  public static void main(String[] argsthrows IOException {
    int value, value2;
    Heap h = new Heap(31)// make a Heap; max size 31
    boolean success;

    h.insert(70)// insert 10 items
    h.insert(40);
    h.insert(50);
    h.insert(20);
    h.insert(60);
    h.insert(100);
    h.insert(80);
    h.insert(30);
    h.insert(10);
    h.insert(90);

    h.displayHeap();
    value = 100;
    success = h.insert(value);
    if (!success)
      System.out.println("Can't insert; heap full");
    if (!h.isEmpty())
      h.remove();
    else
      System.out.println("Can't remove; heap empty");
    value = 80;
    value2 = 999;
    success = h.change(value, value2);
    if (!success)
      System.out.println("Invalid index");
  }
  class Node {
    private int data; 

    public Node(int key) {
      data = key;
    }

    public int getKey() {
      return data;
    }

    public void setKey(int id) {
      data = id;
    }

  }

}

           
         
    
    
  














Related examples in the same category
1.Fibonacci heap data structure
2.Binary Heap Queue
3.Tree Heap
4.This class implements the heap interface using a java.util.List as the underlying data structure.
5.A heap-based priority queue, without any concurrency controlA heap-based priority queue, without any concurrency control
6.Minimum heap implementation.
7.A MinMaxHeap provides a heap-like data structure that provides fast access to both the minimum and maximum elements of the heap.
java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.