All Downloads are FREE. Search and download functionalities are using the official Maven repository.

date.iterator.count.util.HeapArray Maven / Gradle / Ivy

There is a newer version: 1.1.5
Show newest version
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;
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy