基于数组自定义实现一个最大堆,包括入堆,出堆,弹出堆顶元素,打印整个堆功能。
public class MyHeap {
private int[] elem;
private int usedSize=0;
// 初始化一个k大小的数组
public MyHeap(int k){
this.elem = new int[k];
}
//入堆
public boolean offer(int val){
if(isFull()){
throw new RuntimeException("堆为满");
}
this.elem[this.usedSize] = val;
int child = this.usedSize;
adjustUp(child);
this.usedSize++;
return true;
}
//出堆
public int poll(){
if (isEmpty()){
throw new RuntimeException("堆为空");
}
int tmp = this.elem[0];
swap(0,this.usedSize-1);
this.usedSize--;
adjustDown(0,this.usedSize);
return tmp;
}
//弹出堆顶元素
public int peek(){
if (isEmpty()){
throw new RuntimeException("堆为空");
}
return this.elem[0];
}
//打印堆中元素
public String show(){
String str = "";
for (int x: this.elem) {
str += x+" ";
}
return str;
}
//判断堆是否为空
public boolean isEmpty(){
return this.usedSize==0;
}
//判断队列是否为满
public boolean isFull(){
return this.usedSize==this.elem.length;
}
//向上调整
private void adjustUp(int child){
int parent = (child-1)/2;
while (child>0){
if (this.elem[child]>this.elem[parent]){
swap(child,parent);
child = parent;
parent = (child-1)/2;
}else{
break;
}
}
}
//向下调整
private void adjustDown(int parent,int len){
int child = 2*parent+1;
while (child<len){
if (child+1<len && this.elem[child]<this.elem[child+1]){
child++;
}
if (this.elem[child] > this.elem[parent]){
swap(child,parent);
parent = child;
child = 2*parent+1;
}else{
break;
}
}
}
//交换
private void swap(int child,int parent){
int tmp = this.elem[child];
this.elem[child] = this.elem[parent];
this.elem[parent] = tmp;
}
}
我们来看看测试:
public class TestDemo {
public static void main(String[] args) {
MyHeap heap = new MyHeap(7);
heap.offer(1);
heap.offer(55);
heap.offer(16);
heap.offer(34);
heap.offer(78);
heap.offer(36);
heap.offer(7);
System.out.println(heap.peek());
System.out.println(heap.show());
heap.poll();
heap.poll();
heap.poll();
heap.poll();
heap.poll();
heap.poll();
heap.poll();
heap.poll();
}
}
符合预期结果。