Advertisement
Guest User

Untitled

a guest
Feb 29th, 2020
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.24 KB | None | 0 0
  1. public class Mandate<Key extends Comparable<Key>> {
  2. private Key[] pq; // heap-ordered complete binary tree
  3. private int N = 0; // in pq[1..N] with pq[0] unused
  4. public Mandate(int maxN) { pq = (Key[]) new Comparable[maxN+1];
  5. }
  6.  
  7. public boolean isEmpty() {
  8. return N == 0;
  9. }
  10. public int size() {
  11. return N;
  12. }
  13. public void insert(Key v) {
  14. pq[++N] = v;
  15. swim(N);
  16. }
  17. public Key delMax() {
  18. Key max = pq[1];
  19. exch(1, N--);
  20. pq[N+1] = null;
  21. sink(1);
  22. return max;
  23. }
  24.  
  25. private boolean less(int i, int j) {
  26. return pq[i].compareTo(pq[j]) < 0;
  27. }
  28. private void exch(int i, int j) {
  29. Key t = pq[i]; pq[i] = pq[j]; pq[j] = t;
  30. }
  31. private void swim(int k) {
  32. while (k > 1 && less(k/2, k)) {
  33. exch(k/2, k);
  34. k = k/2;
  35. }
  36. }
  37. private void sink(int k) {
  38. while (2*k <= N) {
  39. int j = 2*k;
  40. if (j < N && less(j, j+1)) j++;
  41. if (!less(k, j)) break;
  42. exch(k, j);
  43. k = j;
  44. }
  45. }
  46.  
  47. public static void main(String[] args) {
  48.  
  49. }
  50. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement