详解Java如何实现小顶堆和大顶堆

大顶堆

每个结点的值都大于或等于其左右孩子结点的值

小顶堆

每个结点的值都小于或等于其左右孩子结点的值

对比图

详解Java如何实现小顶堆和大顶堆_第1张图片

实现代码

public class HeapNode{
    private int size;//堆大小
    private int[] heap;//保存堆数组

    //初始化堆
    public HeapNode(int n) {
        heap = new int[n];
        size = 0;
    }

    //小顶堆建堆
    public void minInsert(int key){
        int i = this.size;
        if (i==0) heap[0] = key;
        else {
            while (i>0 && heap[i/2]>key){
                heap[i] = heap[i/2];
                i = i/2;
            }
            heap[i] = key;
        }
        this.size++;
    }

    //大顶堆建堆
    public void maxInsert(int key){
        int i = this.size;
        if (i==0) heap[0] = key;
        else {
            while (i>0 && heap[i/2] heap[i]) max = L;
        else max = i;
        if (R <= size && heap[R] > heap[max]) max = R;
        if (max!=i){
            int t = heap[max];
            heap[max] = heap[i];
            heap[i] = t;
            maxHeapify(max);
        }
    }

    //输出堆
    public void print(){
        for (int i = 0; i < this.size; i++) {
            System.out.print(heap[i]+" ");
        }
        System.out.println();
    }
}

测试

public class Heap {
    static int[] a = {5,3,6,4,2,1};
    static int n = a.length;
    public static void main(String[] args){
        HeapNode heapNode = new HeapNode(n);
        for (int i = 0; i < n; i++) {
            heapNode.maxInsert(a[i]);
        }
        heapNode.print();
        for (int i = 0; i < n; i++) {
            int min = heapNode.maxDelete();
            System.out.print("堆顶:"+min+" 剩下堆元素:");
            heapNode.print();
        }
    }
}

结果

详解Java如何实现小顶堆和大顶堆_第2张图片

到此这篇关于详解Java如何实现小顶堆和大顶堆的文章就介绍到这了,更多相关Java实现小顶堆和大顶堆内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

你可能感兴趣的:(详解Java如何实现小顶堆和大顶堆)