java大根堆实现

在Java中实现一个大根堆(Max Heap),通常我们会定义一个自定义的类来表示堆结构,并实现相关的插入(insert)、删除最大元素(removeMax)以及调整堆(heapify)等方法。以下是一个简单的示例来说明如何实现一个大根堆:

首先,我们定义一个MaxHeap类:

public class MaxHeap {
    private int[] heapArray;
    private int size;
    private int capacity;

    public MaxHeap(int capacity) {
        this.capacity = capacity;
        this.size = 0;
        this.heapArray = new int[capacity];
    }

    // 插入元素
    public void insert(int value) {
        if (size == capacity) {
            throw new IllegalStateException("Heap is full");
        }
        heapArray[size] = value;
        siftUp(size);
        size++;
    }

    // 删除并返回最大元素
    public int removeMax() {
        if (size == 0) {
            throw new IllegalStateException("Heap is empty");
        }
        int max = heapArray[0];
        heapArray[0] = heapArray[--size];
        heapArray[size] = 0; // Optional: help GC
        siftDown(0);
        return max;
    }

    // 上浮操作,保持堆的性质
    private void siftUp(int index) {
        while (index > 0) {
            int parentIndex = (index - 1) / 2;
            if (heapArray[index] > heapArray[parentIndex]) {
                swap(index, parentIndex);
                index = parentIndex;
            } else {
                break;
            }
        }
    }

    // 下沉操作,保持堆的性质
    private void siftDown(int index) {
        int leftChildIndex, rightChildIndex, largestIndex;
        while (true) {
            leftChildIndex = 2 * index + 1;
            rightChildIndex = 2 * index + 2;
            largestIndex = index;

            if (leftChildIndex < size && heapArray[leftChildIndex] > heapArray[largestIndex]) {
                largestIndex = leftChildIndex;
            }

            if (rightChildIndex < size && heapArray[rightChildIndex] > heapArray[largestIndex]) {
                largestIndex = rightChildIndex;
            }

            if (largestIndex == index) {
                break;
            }

            swap(index, largestIndex);
            index = largestIndex;
        }
    }

    // 交换两个元素
    private void swap(int i, int j) {
        int temp = heapArray[i];
        heapArray[i] = heapArray[j];
        heapArray[j] = temp;
    }
}

这个类定义了一个大根堆,其中包含了初始化堆、插入元素、删除最大元素、上浮和下沉等基本操作。insert方法用于向堆中添加元素,并通过siftUp方法维护堆的性质;removeMax方法移除并返回堆顶的最大元素,然后通过siftDown方法调整堆以保持其结构。注意,这里的实现是基于数组的,且为了简单起见,没有实现扩容逻辑,当堆满时会抛出异常。在实际应用中,你可能需要根据需求添加扩容功能。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值