堆的基本操作

package datastructure;

class Heap{
    int[] data;
    int length;
}

class HeapOp{

    public Heap create(Heap heap){
        int n = heap.length;
        for(int i = (n - 1) / 2; i >= 1; i--)
            shiftDown(heap, i);
        return heap;
    }

    public void shiftDown(Heap heap, int i){
        int n = heap.length;
        while(2*i < n){
            int child = 2 * i;
            if(2*i+1 < n && heap.data[2*i+1] > heap.data[2*i])
                child++;
            if(heap.data[child] > heap.data[i]){
                swap(heap.data, i, child);
                i = child;
            }else
                return;
        }
    }
    public void swap(int[] data, int i, int j){
        int t = data[i];
        data[i] = data[j];
        data[j] = t;
    }
    public void print(Heap heap){
        for(int i = 1; i < heap.length; i++){
            System.out.print(heap.data[i] + " ");
        }
        System.out.println();
    }


    public void insert(Heap heap, int key){
        int n = heap.length;
        int[] data = heap.data;
        int i = n;
        while(i != 1 && key > data[i/2]){
            data[i] = data[i/2];
            i /= 2;
        }
        data[i] = key;
        heap.length++;
    }


    public void delete(Heap heap){
        int n = heap.length;
        heap.data[1] = heap.data[n - 1];
        heap.length--;
        shiftDown(heap, 1);
    }
}
public class Heap1 {

    public static void main(String[] args) {
        //最大堆
        //堆从1开始存储数据
        HeapOp h= new HeapOp();
        int[] init = {0, 2, 14, 10, 20, 15};
        int[] data = new int[100];
        for(int i = 1; i < init.length; i++)
            data[i] = init[i];
        //初始化Heap
        Heap initHeap = new Heap();
        initHeap.length = init.length;
        initHeap.data = data;
        //创建
        System.out.println("build heap :");
        Heap heap = h.create(initHeap);
        h.print(heap);
        //插入
        System.out.println("insert heap :");
        int key = 13;
        h.insert(heap, key);
        h.print(heap);
        //删除    最大元素
        System.out.println("delete heap :");
        h.delete(heap);
        h.print(heap);

    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值