二叉堆实现优先队列

JAVA版

public class PQ<Key extends Comparable<Key>> {
  private Key[] pq;
  private int N;

  public PQ(int cap) {
    pq = (Key[]) new Comparable[cap + 1];
  }

  public Key max() {
    return pq[1];
  }

  public void insert(Key e) {
    N++;
    pq[N] = e;
    swim(N);
  }

  public Key delMax() {
    exch(1, N);
    N--;
    sink(1);
    return max();
  }

  private int parent(int k) {
    return k / 2;
  }

  private int left(int root) {
    return root * 2;
  }

  private int right(int root) {
    return root * 2 + 1;
  }

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

  private void sink(int k) {
    while (k <= N) {
      int old = left(k);
      if (right(k) <= N && less(old, right(k))) {
        old = right(k);
      }
      if (less(k, old)) {
        exch(k, old);
        k = old;
      } else {
        break;
      }
    }
  }

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

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

  public static void main(String[] args) {
    PQ<Integer> t = new PQ<>(3);
    t.insert(1);
    t.insert(20);
    t.insert(15);
    System.out.println(t.max());
    System.out.println(t.delMax());
  }

}

posted @ 2020-07-11 11:16  Mikejiawei  阅读(81)  评论(0编辑  收藏  举报