摘要: 本文深入探讨了 Java 中的最大堆方法,阐述了其概念、实现原理以及在实际编程中的广泛应用。通过对最大堆的特性分析,展示了其在高效数据处理、优先队列实现等方面的重要价值,为 Java 开发者提供了深入理解和运用最大堆方法的参考。
PriorityQueue<Integer> maxHeap = new PriorityQueue<>(Collections.reverseOrder());
class MaxHeap {
private int[] heap;
private int size;
public MaxHeap(int capacity) {
heap = new int[capacity];
size = 0;
}
private int parent(int index) {
return (index - 1) / 2;
}
private int leftChild(int index) {
return 2 * index + 1;
}
private int rightChild(int index) {
return 2 * index + 2;
}
private void swap(int i, int j) {
int temp = heap[i];
heap[i] = heap[j];
heap[j] = temp;
}
public void insert(int value) {
if (size == heap.length) {
throw new IllegalStateException("Heap is full");
}
heap[size] = value;
int current = size;
while (current > 0 && heap[current] > heap[parent(current)]) {
swap(current, parent(current));
current = parent(current);
}
size++;
}
public int extractMax() {
if (size == 0) {
throw new IllegalStateException("Heap is empty");
}
int max = heap[0];
heap[0] = heap[size - 1];
size--;
heapify(0);
return max;
}
private void heapify(int index) {
int largest = index;
int left = leftChild(index);
int right = rightChild(index);
if (left < size && heap[left] > heap[largest]) {
largest = left;
}
if (right < size && heap[right] > heap[largest]) {
largest = right;
}
if (largest!= index) {
swap(index, largest);
heapify(largest);
}
}
}