优先队列学习笔记1

public class BinaryHeap<E extends Comparable<T>, T> {

    private static final int DEFAULT_CAPACITY = 10;
    private int currentSize;
    private E[] array;

    // 扩大数组
    private void enlargeArray(int newSize) {

    }

    public BinaryHeap() {

    }

    public BinaryHeap(int capacity) {

    }

    public BinaryHeap(E[] items) {
        currentSize = items.length;
        array = (E[]) new Comparable[(currentSize + 2) * 11 / 10];
        int i = 1;
        for (E item : items)
            array[i++] = item;

        buildHeap();
    }

    // 建堆
    private void buildHeap() {
        for (int i = currentSize / 2; i > 0; i--)
            percolateDown(i);
    }

    // 插入
    public void insert(E e) {
        if (currentSize == array.length - 1)
            enlargeArray(array.length * 2 + 1);// 扩容

        // 上虑
        int hole = ++currentSize; // 空穴
        for (array[0] = e; e.compareTo((T) array[hole / 2]) < 0; hole /= 2)// 如果e比父节点小,空穴就上虑到父节点处,直到e>父节点位置
            array[hole] = array[hole / 2];

        array[hole] = e;// 最后将添加的元素放入空穴处
    }

    public E findMin() {

        return null;
    }

    public E deleteMin() throws Exception {
        if (isEmpty())
            throw new UnderflowException();// 如果为空,报错
        E minItem = findMin();
        array[1] = array[currentSize--];
        percolateDown(1);// 下虑

        return minItem;
    }

    // 下虑 把较小的儿子置入空穴,将空穴下滑一层,至到最后一层建立空穴。
    private void percolateDown(int hole) {
        int child;
        E temp = array[hole];
        for (; hole * 2 <= currentSize; hole = child) {
            child = hole * 2;// 左儿子
            if (child != currentSize && array[child+1].compareTo((T) array[child]) < 0)//该节点没有右儿子
                child++;
            if (array[child].compareTo((T) temp) < 0)
                array[hole] = array[child];
            else
                break;

        }
        array[hole] = temp;
    }

    public boolean isEmpty() {
        return false;
    }

    public void makeEmpty() {

    }

}

猜你喜欢

转载自blog.csdn.net/bushanyantanzhe/article/details/80194999
今日推荐