date.iterator.count.util.HeapArray Maven / Gradle / Ivy
package date.iterator.count.util;
public class HeapArray {
private Integer[] heap = new Integer[10]; //Object
private int size = 16;
private int currentIndex = -1;
//先加入最后,然后调整树结构,根最小
public void add(final int newValue) {
currentIndex ++;
if (currentIndex > size) {
dilatation();
}
heap[currentIndex] = newValue;
rotate();
}
// 1
// 2 3
// 4 5 6 7
// int 除法向下取整,自动保证了+1的子节点位置
private void rotate() {
int newValueLocation = currentIndex;
int value = heap[newValueLocation];
while (newValueLocation > 0 && heap[newValueLocation] < heap[newValueLocation / 2]) {
int nextLocation = newValueLocation / 2;
heap[newValueLocation] = heap[newValueLocation / 2];
newValueLocation = nextLocation;
}
heap[newValueLocation] = value;
}
private void dilatation() {
final Integer[] new_heap = new Integer[heap.length * 2];
System.arraycopy(heap, 0, new_heap, 0, heap.length);
heap = new_heap;
}
}