算法-堆的实现

 

 

package test.tree;

public class Heap<T extends Comparable<T>> {
    //储存堆中的元素
    private T[] items;
    private int N;

    public Heap(int capacity){
        items = (T[])new Comparable[capacity+1];
        N = 0;
    }

    private boolean less(int i,int j){
        return items[i].compareTo(items[j])<0;

    }

    private void exch(int i,int j){
        T temp = items[i];
        items[i] = items[j];
        items[j] = temp;
    }

    public void insert(T t){
        items[++N] = t;
        swim(N);

    }
    //使用上浮算法,使索引k处的元素可以在堆中处于一个正确的元素
    private void swim(int k){
        while (k>1){
            if(less(k/2,k)){
                exch(k/2,k);
            }
            k=k/2;
        }
    }

    //删除堆中最大元素,并返回这个最大元素
    public T delMax(){
      T max =  items[1];
      items[1] = items[N];
      items[N] = null;
        N--;
      sink(1);

      return max;
    }

    private  void sink(int k){
        while (2*k<N){
            int max ;
            if(2*k+1<=N){
                if(less(2*k,2*k+1)){
                    max = 2*k+1;
                }else{
                    max = 2*k;
                }
            }else{
                max = 2*k;
            }
            if(less(k,max)){
                exch(k,max);
                k = max;
            }else{
                break;
            }

        }

    }

}

package test.tree;

public class HeapTest  {
    public static void main(String[] args) {
        Heap<String> heap = new Heap<String>(10);
        heap.insert("a");
        heap.insert("b");
        heap.insert("c");
        heap.insert("d");
        heap.insert("e");
        heap.insert("f");
        heap.insert("g");
        heap.insert("h");
        heap.insert("i");
        String result = null;
        while ((result = heap.delMax())!=null){
            System.out.println(result+"");
        }





    }
}


结果
i
h
g
f
e
d
c
b
a

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值