堆的实现-基于数组
package com.gm.heap;
import java.util.ArrayList;
import java.util.List;
public class HelloHeap {
private int[] heap;
private int size;
private int capacity;
public HelloHeap(int capacity) {
if (capacity < 2) {
throw new RuntimeException("堆容量至少为2");
}
this.capacity = capacity;
this.heap = new int[capacity];
this.size = 0;
}
public void printAll() {
List<Integer> everyFloorFirstIndex = new ArrayList<>();
for (int i = 0; i < size; i++) {
everyFloorFirstIndex.add((int) Math.pow(2, i));
}
for (int index = 1; index < size + 1; index++) {
if (everyFloorFirstIndex.contains(index)) {
System.out.println();
}
System.out.print(" " + this.heap[index]);
}
System.out.println();
}
public boolean insert(int val) {
if (this.capacity - 1 == this.size) {
System.out.println("堆已满");
return false;
}
int curIndex = this.size + 1;
this.heap[curIndex] = val;
while (curIndex / 2 > 0 && val > this.heap[curIndex / 2]) {
int parentVal = this.heap[curIndex / 2];
this.heap[curIndex / 2] = val;
this.heap[curIndex] = parentVal;
curIndex = curIndex / 2;
}
++size;
return true;
}
public boolean deleteHead() {
if (this.size == 0) {
return false;
}
this.heap[1] = this.heap[size];
--this.size;
int curIndex = 1;
while (true) {
if (curIndex * 2 > this.size) {
break;
}
if (curIndex * 2 < this.size) {
if (this.heap[curIndex * 2] > this.heap[curIndex * 2 + 1]) {
swap(curIndex, curIndex * 2);
curIndex = curIndex * 2;
} else {
swap(curIndex, curIndex * 2 + 1);
curIndex = curIndex * 2 + 1;
}
continue;
}
if (curIndex * 2 == this.size) {
if (this.heap[curIndex * 2] > this.heap[curIndex]) {
swap(curIndex, curIndex * 2);
}
}
curIndex = curIndex * 2;
}
return true;
}
private void swap(int curIndex, int target) {
int tmp = this.heap[curIndex];
this.heap[curIndex] = this.heap[target];
this.heap[target] = tmp;
}
public static void main(String[] args) {
HelloHeap helloHeap10 = new HelloHeap(20);
helloHeap10.insert(3);
helloHeap10.insert(2);
helloHeap10.insert(1);
helloHeap10.insert(4);
helloHeap10.insert(5);
helloHeap10.insert(6);
helloHeap10.insert(7);
helloHeap10.printAll();
System.out.println("删除结果:" + helloHeap10.deleteHead());
helloHeap10.printAll();
}
}