1 22 package org.jboss.util; 23 24 import java.util.Comparator ; 25 26 35 public class Heap 36 { 37 private Comparator m_comparator; 38 private int m_count; 39 private Object [] m_nodes; 40 41 45 public Heap() 46 { 47 this(null); 48 } 49 50 54 public Heap(Comparator comparator) 55 { 56 m_comparator = comparator; 57 clear(); 58 } 59 60 65 public void insert(Object obj) 66 { 67 int length = m_nodes.length; 68 if (m_count == length) 70 { 71 Object [] newNodes = new Object [length + length]; 72 System.arraycopy(m_nodes, 0, newNodes, 0, length); 73 m_nodes = newNodes; 74 } 75 int k = m_count; 83 while (k > 0) 84 { 85 int par = parent(k); 86 if (compare(obj, m_nodes[par]) < 0) 87 { 88 m_nodes[k] = m_nodes[par]; 89 k = par; 90 } 91 else break; 92 } 93 m_nodes[k] = obj; 94 ++m_count; 95 } 96 97 103 public Object extract() 104 { 105 if (m_count < 1) {return null;} 106 else 107 { 108 int length = m_nodes.length >> 1; 109 if (length > 5 && m_count < (length >> 1)) 111 { 112 Object [] newNodes = new Object [length]; 113 System.arraycopy(m_nodes, 0, newNodes, 0, length); 114 m_nodes = newNodes; 115 } 116 int k = 0; 118 Object ret = m_nodes[k]; 119 --m_count; 120 Object last = m_nodes[m_count]; 121 for (;;) 122 { 123 int l = left(k); 124 if (l >= m_count) {break;} 125 else 126 { 127 int r = right(k); 128 int child = (r >= m_count || compare(m_nodes[l], m_nodes[r]) < 0) ? l : r; 129 if (compare(last, m_nodes[child]) > 0) 130 { 131 m_nodes[k] = m_nodes[child]; 132 k = child; 133 } 134 else {break;} 135 } 136 } 137 m_nodes[k] = last; 138 m_nodes[m_count] = null; 139 return ret; 140 } 141 } 142 143 148 public Object peek() 149 { 150 if (m_count < 1) {return null;} 151 else {return m_nodes[0];} 152 } 153 154 157 public void clear() 158 { 159 m_count = 0; 160 m_nodes = new Object [10]; 161 } 162 163 170 protected int compare(Object o1, Object o2) 171 { 172 if (m_comparator != null) 173 { 174 return m_comparator.compare(o1, o2); 175 } 176 else 177 { 178 if (o1 == null) 179 { 180 if (o2 == null) {return 0;} 181 else {return -((Comparable )o2).compareTo(o1);} 182 } 183 else {return ((Comparable )o1).compareTo(o2);} 184 } 185 } 186 187 190 protected int parent(int index) 191 { 192 return (index - 1) >> 1; 193 } 194 195 198 protected int left(int index) 199 { 200 return index + index + 1; 201 } 202 203 206 protected int right(int index) 207 { 208 return index + index + 2; 209 } 210 } 211 | Popular Tags |