详解Java如何实现小顶堆和大顶堆
作者:HSBhuang 时间:2023-11-10 04:03:05
大顶堆
每个结点的值都大于或等于其左右孩子结点的值
小顶堆
每个结点的值都小于或等于其左右孩子结点的值
对比图
实现代码
public class HeapNode{
private int size;//堆大小
private int[] heap;//保存堆数组
//初始化堆
public HeapNode(int n) {
heap = new int[n];
size = 0;
}
//小顶堆建堆
public void minInsert(int key){
int i = this.size;
if (i==0) heap[0] = key;
else {
while (i>0 && heap[i/2]>key){
heap[i] = heap[i/2];
i = i/2;
}
heap[i] = key;
}
this.size++;
}
//大顶堆建堆
public void maxInsert(int key){
int i = this.size;
if (i==0) heap[0] = key;
else {
while (i>0 && heap[i/2]<key){
heap[i] = heap[i/2];
i = i/2;
}
heap[i] = key;
}
this.size++;
}
//小顶堆删除
public int minDelete(){
if (this.size==0) return -1;
int top = heap[0];
int last = heap[this.size-1];
heap[0] = last;
this.size--;
//堆化
minHeapify(0);
return top;
}
//大顶堆删除
public int maxDelete(){
if (this.size==0) return -1;
int top = heap[0];
int last = heap[this.size-1];
heap[0] = last;
this.size--;
//堆化
maxHeapify(0);
return top;
}
//小顶堆化
public void minHeapify(int i){
int L = 2*i,R=2*i+1,min;
if (L<=size && heap[L] < heap[i]) min = L;
else min = i;
if (R <= size && heap[R] < heap[min]) min = R;
if (min!=i){
int t = heap[min];
heap[min] = heap[i];
heap[i] = t;
minHeapify(min);
}
}
//大顶堆化
public void maxHeapify(int i){
int L = 2*i,R=2*i+1,max;
if (L<=size && heap[L] > heap[i]) max = L;
else max = i;
if (R <= size && heap[R] > heap[max]) max = R;
if (max!=i){
int t = heap[max];
heap[max] = heap[i];
heap[i] = t;
maxHeapify(max);
}
}
//输出堆
public void print(){
for (int i = 0; i < this.size; i++) {
System.out.print(heap[i]+" ");
}
System.out.println();
}
}
测试
public class Heap {
static int[] a = {5,3,6,4,2,1};
static int n = a.length;
public static void main(String[] args){
HeapNode heapNode = new HeapNode(n);
for (int i = 0; i < n; i++) {
heapNode.maxInsert(a[i]);
}
heapNode.print();
for (int i = 0; i < n; i++) {
int min = heapNode.maxDelete();
System.out.print("堆顶:"+min+" 剩下堆元素:");
heapNode.print();
}
}
}
结果
来源:https://blog.csdn.net/HSBhuang/article/details/117929543
标签:Java,小顶堆,大顶堆
0
投稿
猜你喜欢
Java ArrayList类的基础使用讲解
2021-11-14 10:22:18
C#开发之Socket网络编程TCP/IP层次模型、端口及报文等探讨
2023-03-28 14:49:53
C# Stream 和 byte[] 之间的转换
2023-06-24 23:14:52
springboot更新配置Swagger3的一些小技巧
2023-08-28 06:31:43
计算字符串和文件MD5值的小例子
2023-12-10 20:31:19
Java这个名字的来历与优势
2023-03-27 18:28:40
Java使用备忘录模式实现过关类游戏功能详解
2022-11-30 08:52:51
c#自定义Attribute获取接口实现示例代码
2022-09-02 05:05:26
Mybatis基于注解形式的sql语句生成实例代码
2023-03-07 03:48:11
Android 显示和隐藏输入法实现代码
2023-03-29 06:42:39
在WCF数据访问中使用缓存提高Winform字段中文显示速度的方法
2022-11-08 10:05:09
android Handler详细使用方法实例
2022-11-29 01:35:12
Android 使用FragmentTabhost代替Tabhost
2021-09-10 19:10:26
SpringBoot 配置文件总结
2021-09-06 13:12:57
Android开发实现TextView超链接5种方式源码实例
2022-12-10 16:50:32
Unity实现场景加载功能
2021-09-15 12:27:45
基于java中cookie和session的比较
2021-08-17 00:49:44
Java流程控制语句之If选择结构
2023-11-11 04:02:29
四种引用类型在JAVA Springboot中的使用详解
2023-11-24 03:34:38
Android RxJava与Retrofit结合使用详解
2021-10-19 20:10:53