1 package org.apache.lucene.util; 2 3 18 19 22 public abstract class PriorityQueue { 23 private Object [] heap; 24 private int size; 25 private int maxSize; 26 27 29 protected abstract boolean lessThan(Object a, Object b); 30 31 32 protected final void initialize(int maxSize) { 33 size = 0; 34 int heapSize = maxSize + 1; 35 heap = new Object [heapSize]; 36 this.maxSize = maxSize; 37 } 38 39 44 public final void put(Object element) { 45 size++; 46 heap[size] = element; 47 upHeap(); 48 } 49 50 56 public boolean insert(Object element){ 57 if(size < maxSize){ 58 put(element); 59 return true; 60 } 61 else if(size > 0 && !lessThan(element, top())){ 62 heap[1] = element; 63 adjustTop(); 64 return true; 65 } 66 else 67 return false; 68 } 69 70 71 public final Object top() { 72 if (size > 0) 73 return heap[1]; 74 else 75 return null; 76 } 77 78 80 public final Object pop() { 81 if (size > 0) { 82 Object result = heap[1]; heap[1] = heap[size]; heap[size] = null; size--; 86 downHeap(); return result; 88 } else 89 return null; 90 } 91 92 99 public final void adjustTop() { 100 downHeap(); 101 } 102 103 104 105 public final int size() { 106 return size; 107 } 108 109 110 public final void clear() { 111 for (int i = 0; i <= size; i++) 112 heap[i] = null; 113 size = 0; 114 } 115 116 private final void upHeap() { 117 int i = size; 118 Object node = heap[i]; int j = i >>> 1; 120 while (j > 0 && lessThan(node, heap[j])) { 121 heap[i] = heap[j]; i = j; 123 j = j >>> 1; 124 } 125 heap[i] = node; } 127 128 private final void downHeap() { 129 int i = 1; 130 Object node = heap[i]; int j = i << 1; int k = j + 1; 133 if (k <= size && lessThan(heap[k], heap[j])) { 134 j = k; 135 } 136 while (j <= size && lessThan(heap[j], node)) { 137 heap[i] = heap[j]; i = j; 139 j = i << 1; 140 k = j + 1; 141 if (k <= size && lessThan(heap[k], heap[j])) { 142 j = k; 143 } 144 } 145 heap[i] = node; } 147 } 148 | Popular Tags |