Implements a Priority Queue ordered that iterates over the smallest key. - Java Data Structure

Java examples for Data Structure:queue

Description

Implements a Priority Queue ordered that iterates over the smallest key.

Demo Code


import java.util.NoSuchElementException;

class PriorityQueue<Key extends Comparable<Key>> {

  private Key[] myQueue;
  private int N;

  public PriorityQueue() {
    this(1);/*  w  w w .ja  v  a  2 s  .  c o m*/
  }

  @SuppressWarnings("unchecked")
  public PriorityQueue(int capacity) {
    myQueue = (Key[]) new Comparable[capacity + 1];
  }

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

  public void insert(Key x) {
    if (N == myQueue.length - 1)
      resize(2 * myQueue.length);

    myQueue[++N] = x;
    swim(N);
  }

  public Key delMin() {
    if (isEmpty())
      throw new NoSuchElementException();

    exch(1, N);
    Key min = myQueue[N--];
    sink(1);
    myQueue[N + 1] = null;

    if ((N > 0) && (N == (myQueue.length - 1) / 4))
      resize(myQueue.length / 2);

    return min;
  }

  private void swim(int k) {
    while (k > 1 && less(k, k / 2)) {
      exch(k / 2, k);
      k = k / 2;
    }
  }

  private void sink(int k) {
    while (2 * k <= N) {
      int j = 2 * k;

      if (j < N && less(j + 1, j))
        j++;

      if (!less(j, k))
        break;

      exch(k, j);
      k = j;
    }
  }

  private boolean less(int i, int j) {
    return myQueue[i].compareTo(myQueue[j]) < 0;
  }

  private void exch(int i, int j) {
    Key swap = myQueue[i];
    myQueue[i] = myQueue[j];
    myQueue[j] = swap;
  }

  private void resize(int capacity) {
    @SuppressWarnings("unchecked")
    Key[] copy = (Key[]) new Comparable[capacity];

    for (int i = 1; i <= N; i++)
      copy[i] = myQueue[i];

    myQueue = copy;
  }

  public static void main(String[] args) {
    PriorityQueue<String> queue = new PriorityQueue<String>();
    queue.insert("P");
    queue.insert("R");
    queue.insert("I");
    queue.insert("O");
    queue.insert("R");
    queue.insert("I");
    queue.insert("T");
    queue.insert("Y");
    queue.insert("Q");
    queue.insert("U");
    queue.insert("E");
    queue.insert("U");
    queue.insert("E");

    while (!queue.isEmpty()) {
      System.out.printf("%s ", queue.delMin());
    }
  }
}

Related Tutorials