以下是使用Java实现堆的示例代码:
public class Heap {
private int[] heapArray;
private int maxSize;
private int currentSize;
public Heap(int maxSize) {
this.maxSize = maxSize;
this.currentSize = 0;
heapArray = new int[maxSize];
}
public boolean isEmpty() {
return currentSize == 0;
}
public boolean isFull() {
return currentSize == maxSize;
}
public void insert(int value) {
if (isFull()) {
System.out.println("Heap is full. Cannot insert more elements.");
return;
}
heapArray[currentSize] = value;
trickleUp(currentSize);
currentSize++;
}
private void trickleUp(int index) {
int parentIndex = (index - 1) / 2;
int bottom = heapArray[index];
while (index > 0 && heapArray[parentIndex] < bottom) {
heapArray[index] = heapArray[parentIndex];
index = parentIndex;
parentIndex = (index - 1) / 2;
}
heapArray[index] = bottom;
}
public int remove() {
if (isEmpty()) {
throw new IllegalStateException("Heap is empty. Cannot remove elements.");
}
int root = heapArray[0];
heapArray[0] = heapArray[currentSize - 1];
currentSize--;
trickleDown(0);
return root;
}
private void trickleDown(int index) {
int top = heapArray[index];
int largerChildIndex;
while (index < currentSize / 2) {
int leftChildIndex = 2 * index + 1;
int rightChildIndex = 2 * index + 2;
if (rightChildIndex < currentSize && heapArray[leftChildIndex] < heapArray[rightChildIndex]) {
largerChildIndex = rightChildIndex;
} else {
largerChildIndex = leftChildIndex;
}
if (top >= heapArray[largerChildIndex]) {
break;
}
heapArray[index] = heapArray[largerChildIndex];
index = largerChildIndex;
}
heapArray[index] = top;
}
public void display() {
for (int i = 0; i < currentSize; i++) {
System.out.print(heapArray[i] + " ");
}
System.out.println();
}
public static void main(String[] args) {
Heap heap = new Heap(10);
heap.insert(4);
heap.insert(10);
heap.insert(8);
heap.insert(15);
heap.insert(6);
heap.insert(12);
heap.display(); // 输出:15 10 12 4 6 8
heap.remove();
heap.display(); // 输出:12 10 8 4 6
}
}
这个示例中,我们定义了一个Heap类来表示堆。堆的大小由maxSize指定,当前堆中的元素个数由currentSize指定。我们使用一个整型数组heapArray来存储堆中的元素。插入操作使用trickleUp方法向上调整堆,从而保持堆的属性。删除操作使用trickleDown方法向下调整堆,从而维护堆的属性。
在main方法中,我们创建了一个堆对象,插入了一些元素,并展示了堆的状态。然后,我们从堆中移除一个元素,并再次展示了堆的状态。
希望这个示例对你有帮助!