数据结构——堆
creat —— 创建堆
show —— 按层输出堆
push —— 入堆
pop —— 出堆
getTop —— 拿堆顶
public class test {
public static void main(String[] args) {
TestHeap testHeap = new TestHeap();
int[] array = {27, 15, 19, 18, 28, 34, 65, 49, 25, 37};
testHeap.creatHeap(array);
testHeap.show();
testHeap.push(80);
testHeap.show();
testHeap.pop();
testHeap.show();
System.out.println(testHeap.getTop());
}
out:
65 49 34 25 37 27 19 18 15 28
80 65 34 25 49 27 19 18 15 28 37
65 49 34 25 37 27 19 18 15 28
65
package 堆;
import java.util.Arrays;
/**
* @author :ZXY
* @date :Created in 2020/9/6 17:59
* @description:
*/
public class TestHeap {
public int[] elem;
public int usedSize;
public TestHeap() {
this.elem=new int[10];
this.usedSize=0;
}
//创建堆
public void creatHeap(int[] array){
for(int i=0;i<array.length;i++){
this.elem[i]=array[i];
this.usedSize++;
}
// i 表示每棵子树的根节点
for(int i=(this.usedSize-1-1)/2;i>=0;i--){
adjustDown(i,this.usedSize);
}
}
//向下调整 root每棵子树根节点 len每棵子树结束位置
public void adjustDown(int root,int len){
int parent=root;
int child=2*parent+1;
while (child<len){
//1、找到左右孩子的最大值
if((child+1<len) && this.elem[child]<this.elem[child+1]){
child=child+1;
}
//child保存左右孩子最大值下标
if(this.elem[child]>this.elem[parent]){
int tmp=this.elem[child];
this.elem[child]=this.elem[parent];
this.elem[parent]=tmp;
parent=child;
child=2*parent+1;
}else{
//不需进行调整
break;
}
}
}
//添加元素
public void push(int val){
if(isFull()){
this.elem=Arrays.copyOf(this.elem,2*this.elem.length);
}
this.elem[usedSize]=val;
this.usedSize++;
adjustUp(this.usedSize-1);
}
public boolean isFull(){
return this.usedSize==this.elem.length;
}
//向上调整
public void adjustUp(int child) {
int parent=(child-1)/2;
while(child>0){
if(this.elem[child]>this.elem[parent]){
int tmp=this.elem[child];
this.elem[child]=this.elem[parent];
this.elem[parent]=tmp;
child=parent;
parent=(child-1)/2;
}else {
break;
}
}
}
public void show(){
for (int i = 0; i <this.usedSize ; i++) {
System.out.print(this.elem[i]+" ");
}
System.out.println();
}
//删除堆顶
public void pop(){
if(isEmpty()){
System.out.println("堆为空");
}
this.elem[0]=this.elem[this.usedSize-1];
this.usedSize--;
adjustDown(0,this.usedSize);
}
public boolean isEmpty(){
return this.usedSize==0;
}
//得到堆顶
public int getTop(){
if(isEmpty()){
System.out.println("堆为空");
}
return this.elem[0];
}
}