//最大堆,数组实现完全二叉堆
public class MaxHeap {
int[] data;// data[0]为最大堆的数量
int capacity;//最大堆的容量
public MaxHeap(int capacity) {
this.capacity = capacity;
data = new int[capacity + 1];
data[0] = 0;
}
//heapfiy
public MaxHeap(int[] arr) {
this.capacity = arr.length;
data = new int[arr.length + 1];
data[0] = arr.length;
for (int i = 0; i < arr.length; i++)
data[i + 1] = arr[i];
}
public static void main(String[] args) {
MaxHeap heap = new MaxHeap(10);
int size = heap.size();
boolean bool = heap.isEmpty();
heap.insert(15);
heap.insert(12);
heap.insert(11);
heap.insert(16);
for (int j = 1; j <= heap.data[0]; j++)
System.out.println(heap.data[j]);
int max = heap.extractMax();
for (int j = 1; j <= heap.data[0]; j++)
System.out.println(heap.data[j]);
}
public int extractMax() {
if (data[0] > 0) {
int max = data[1];
data[1] = data[data[0]];
data[0]--;
shiftDown(1);
return max;
}
return Integer.MAX_VALUE;
}
public void shiftDown(int i) {
while (i * 2 <= data[0]) {
int j = i * 2;
if (j + 1 <= data[0])
if (data[j + 1] > data[j])
j += 1;
if (data[i] < data[j]) {
swap(i, j);
i = j;
} else
break;
}
}
public void insert(int i) {
if (capacity >= data[0] + 1) {
data[++data[0]] = i;
shiftUp(data[0]);
}
}
private void shiftUp(int i) {
while (i > 1 && data[i / 2] < data[i]) {
swap(i / 2, i);
i /= 2;
}
}
private void swap(int i, int j) {
data[i] = data[i] ^ data[j];
data[j] = data[i] ^ data[j];
data[i] = data[i] ^ data[j];
}
public boolean isEmpty() {
return data[0] == 0;
}
public int size() {
return data[0];
}
}