集册 Java实例教程 实现一个优先级队列,该队列按顺序遍历最小的密钥。

实现一个优先级队列,该队列按顺序遍历最小的密钥。

欢马劈雪     最近更新时间:2020-01-02 10:19:05

560
实现一个优先级队列,该队列按顺序遍历最小的密钥。


import java.util.NoSuchElementException;
/**时代Java - nowjava.com**/

class PriorityQueue<Key extends Comparable<Key>> {


  private Key[] myQueue;

  private int N;


  public PriorityQueue() {

    this(1);

  }


  @SuppressWarnings("unchecked")

  public PriorityQueue(int capacity) {

    myQueue = (Key[]) new Comparable[capacity + 1];

  }


  public boolean isEmpty() {

    return N == 0;

  }


  public void insert(Key x) {/* 来 自 nowjava.com - 时代Java*/

    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");

    que
展开阅读全文