最小堆

转载:http://blog.csdn.net/cangyingzhijia/article/details/4925331

堆作为重要的数据结构之一,分为最大堆和最小堆是二叉堆 的两种形式。

  1. 最大堆 :根结点的键值是所有堆结点键值中最大者的堆。
  2. 最小堆 :根结点的键值是所有堆结点键值中最小者的堆。

下面是引自wikipedia的最小堆示例图:

public class SmallHeap {
    
    final static int MAX_LEN = 100;
    private int queue[] = new int[MAX_LEN];
    private int size;
    
    public void add(int e){
        if(size >= MAX_LEN)
        {
            System.err.println("over flow");
            return;
        }
        int s = size++;        
        shiftup(s,e);
    }
    
    public int size(){
        return size;
    }
    
    private void shiftup(int s, int e) {     //插入节点,向上调整
        while(s > 0){
            int parent = (s - 1)/2;        //取父节点
            if(queue[parent] < e){       //父节点比插入节点小,直接插入节点在尾部
                break;
            }
            queue[s] = queue[parent];   //如果父节点比插入节点大,把父节点赋值给子节点,再取祖父节点比较
            s = parent;
            
        }
        queue[s] = e;
        
    }
    public int poll(){
        if(size <= 0)
            return -1;
        int ret = queue[0];
        int s = --size;
        shiftdown(0, queue[s]);
        queue[s] = 0;        
        return ret;
    }
    
    private void shiftdown(int i, int e) {
        int half = size /2;
        while(i < half ){
            int child = 2*i +1;       //左子节点
            int right = child +1;    //右子结点
            if(right < size && queue[child] > queue[right]){  //取左右节点中较小的值
                child = right;
            }
            if(e < queue[child]){     //最后一个节点比子节点小,直接用最后一个节点做根
                break;
            }
            queue[i] = queue[child];  //否则把子节点赋值给父节点并向下走
            i = child;            
        }        
        
        queue[i] = e;
                        
    }
    public static void main(String args[]){
        SmallHeap hs = new SmallHeap();
        hs.add(4);
        hs.add(3);
        hs.add(7);
        hs.add(2);
        int size = hs.size();
        for(int i=0; i< size; i++){
            System.out.println(hs.poll());
        }        
        
    }
    
    
}
posted @ 2012-10-07 13:46  三块钱的其其  阅读(157)  评论(0编辑  收藏  举报