最大堆java

最大堆(Max-Heap)是一種二叉堆,其中每個節點的值都不小於其子節點的值。在最大堆中,根節點是最大值。最大堆可以用來實現優先佇列,其中刪除最大元素(即堆頂元素)的過程可以在對數時間內完成。

在Java中,可以使用數組來實現最大堆。以下是一個簡單的最大堆實現示例:

import java.util.Arrays;

public class MaxHeap {
    private int[] heap;
    private int size;

    public MaxHeap(int capacity) {
        heap = new int[capacity + 1]; // 最後一個元素是哨兵
        size = 0;
    }

    public void insert(int value) {
        if (size == heap.length - 1) {
            throw new IllegalStateException("Heap is full");
        }
        size++;
        heap[size] = value;
        int parentIndex = (size - 1) / 2;
        while (parentIndex >= 0 && heap[parentIndex] < heap[size]) {
            swap(parentIndex, size);
            size--;
            parentIndex = (size - 1) / 2;
        }
    }

    public int extractMax() {
        if (size == 0) {
            throw new IllegalStateException("Heap is empty");
        }
        int max = heap[1];
        swap(1, size);
        size--;
        heapifyDown(1);
        return max;
    }

    private void swap(int i, int j) {
        int temp = heap[i];
        heap[i] = heap[j];
        heap[j] = temp;
    }

    private void heapifyDown(int parentIndex) {
        int childIndex = 2 * parentIndex;
        while (childIndex <= size) {
            int maxChildIndex = childIndex;
            if (childIndex < size && heap[childIndex] < heap[childIndex + 1]) {
                maxChildIndex++;
            }
            if (heap[parentIndex] < heap[maxChildIndex]) {
                swap(parentIndex, maxChildIndex);
                parentIndex = maxChildIndex;
                childIndex = 2 * parentIndex;
            } else {
                break;
            }
        }
    }

    public int size() {
        return size;
    }

    public boolean isEmpty() {
        return size == 0;
    }

    public void printHeap() {
        System.out.println(Arrays.toString(heap));
    }
}

在這個實現中,我們使用了一個哨兵(即最後一個元素)來簡化堆頂元素的刪除過程。當我們插入新元素時,我們將其直接放在數組的末尾,然後通過上浮操作將其調整到正確的位置。當我們刪除堆頂元素時,我們直接返回該元素,並將最後一個元素移動到堆頂,然後通過下沉操作調整堆。

請注意,這個實現沒有提供刪除特定元素的方法,因為它只支持刪除堆頂元素。如果你需要支持刪除特定元素,你可能需要使用其他數據結構或調整最大堆的實現。