向下调整建小根堆的Java代码
时间: 2024-06-12 18:08:24 浏览: 51
下面是建立小根堆的Java代码示例:
```
public class MinHeap {
private int[] heap;
private int size;
private int capacity;
public MinHeap(int capacity) {
this.capacity = capacity;
this.size = 0;
this.heap = new int[capacity + 1];
}
public void insert(int value) {
if (size >= capacity) {
return;
}
size++;
int index = size;
heap[index] = value;
while (index > 1 && heap[index] < heap[index / 2]) {
swap(index, index / 2);
index = index / 2;
}
}
public void heapify(int index) {
int smallest = index;
int left = 2 * index;
int right = 2 * index + 1;
if (left <= size && heap[left] < heap[smallest]) {
smallest = left;
}
if (right <= size && heap[right] < heap[smallest]) {
smallest = right;
}
if (smallest != index) {
swap(index, smallest);
heapify(smallest);
}
}
public int extractMin() {
if (size == 0) {
return -1;
}
int min = heap[1];
heap[1] = heap[size];
size--;
heapify(1);
return min;
}
private void swap(int i, int j) {
int temp = heap[i];
heap[i] = heap[j];
heap[j] = temp; }
}
```
阅读全文