1 15 16 package EDU.oswego.cs.dl.util.concurrent; 17 import java.util.Comparator ; 18 19 30 31 public class Heap { 32 protected Object [] nodes_; protected int count_ = 0; protected final Comparator cmp_; 36 40 41 public Heap(int capacity, Comparator cmp) 42 throws IllegalArgumentException { 43 if (capacity <= 0) throw new IllegalArgumentException (); 44 nodes_ = new Object [capacity]; 45 cmp_ = cmp; 46 } 47 48 52 53 public Heap(int capacity) { 54 this(capacity, null); 55 } 56 57 58 59 protected int compare(Object a, Object b) { 60 if (cmp_ == null) 61 return ((Comparable )a).compareTo(b); 62 else 63 return cmp_.compare(a, b); 64 } 65 66 67 protected final int parent(int k) { return (k - 1) / 2; } 69 protected final int left(int k) { return 2 * k + 1; } 70 protected final int right(int k) { return 2 * (k + 1); } 71 72 75 public synchronized void insert(Object x) { 76 if (count_ >= nodes_.length) { 77 int newcap = 3 * nodes_.length / 2 + 1; 78 Object [] newnodes = new Object [newcap]; 79 System.arraycopy(nodes_, 0, newnodes, 0, nodes_.length); 80 nodes_ = newnodes; 81 } 82 83 int k = count_; 84 ++count_; 85 while (k > 0) { 86 int par = parent(k); 87 if (compare(x, nodes_[par]) < 0) { 88 nodes_[k] = nodes_[par]; 89 k = par; 90 } 91 else break; 92 } 93 nodes_[k] = x; 94 } 95 96 97 100 101 public synchronized Object extract() { 102 if (count_ < 1) return null; 103 104 int k = 0; Object least = nodes_[k]; 106 --count_; 107 Object x = nodes_[count_]; 108 nodes_[count_] = null; 109 for (;;) { 110 int l = left(k); 111 if (l >= count_) 112 break; 113 else { 114 int r = right(k); 115 int child = (r >= count_ || compare(nodes_[l], nodes_[r]) < 0)? l : r; 116 if (compare(x, nodes_[child]) > 0) { 117 nodes_[k] = nodes_[child]; 118 k = child; 119 } 120 else break; 121 } 122 } 123 nodes_[k] = x; 124 return least; 125 } 126 127 128 public synchronized Object peek() { 129 if (count_ > 0) 130 return nodes_[0]; 131 else 132 return null; 133 } 134 135 136 public synchronized int size() { 137 return count_; 138 } 139 140 141 public synchronized void clear() { 142 for (int i = 0; i < count_; ++i) 143 nodes_[i] = null; 144 count_ = 0; 145 } 146 147 } 148 | Popular Tags |