最大堆
public class MaxHeap {
private static int size = 0;
private void maxHeap(int k, Integer key, Integer[] array){
while (k > 0){
//父节点,即array的中点
int parent = (k - 1) >>> 1;
Integer e= array[parent];
if (key.compareTo(e) <= 0){
break;
}
array[k] = e;
k = parent;
}
array[k] = key;
++size;
}
public static void main(String[] args) {
MaxHeap maxHeap = new MaxHeap();
Integer[] array = new Integer[10];
maxHeap.maxHeap(size,2,array);
maxHeap.maxHeap(size,4,array);
maxHeap.maxHeap(size,6,array);
maxHeap.maxHeap(size,1,array);
maxHeap.maxHeap(size,4,array);
for (int i = 0; i< size; i++){
System.out.print(array[i] + "\t");
//output 6 4 4 1 2
}
}
}
最小堆
将上述代码中的
if (key.compareTo(e) <= 0){
break;
}
改为如下,即建立最小堆
if (key.compareTo(e) >= 0){
break;
}