当前位置:网站首页>大根堆的创建(视频讲解)
大根堆的创建(视频讲解)
2022-07-30 09:15:00 【学习追求高效率】
大根堆的创建2
注意:
- 其实左右节点 都是要去找父亲节点,不如遍历的时候,就通过父亲节点遍历(可以减少遍历次数以及 遍历经过中的循环次数)
for (int parent = (usedSize-1-1) / 2; parent >= 0 ; parent--)
public class TestHeap {
public int[] elem;
public int usedSize;//当前堆当中的有效的元素的数据个数
public TestHeap() {
this.elem = new int[10];
this.usedSize = 0;
}
public void initArray(int[] array) {
elem = Arrays.copyOf(array,array.length);
usedSize = elem.length;
}
/** * 建堆:【大根堆】 * 时间复杂度:O(n) */
public void createHeap() {
for (int parent = (usedSize-1-1) / 2; parent >= 0 ; parent--) {
shiftDown(parent,usedSize);
}
}
/** * 实现 向下调整 * @param parent 每棵子树的根节点的下标 * @param len 每棵子树的结束位置 */
private void shiftDown(int parent ,int len) {
int child = 2 * parent + 1;
//最起码是有左孩子
while (child < len) {
//判断 左孩子 和 右孩子 谁最大,前提是 必须有 右孩子
if(child+1 < len && elem[child] < elem[child+1]) {
child++;//此时 保存了最大值的下标
}
if(elem[child] > elem[parent]) {
swap(elem,child,parent);
parent = child;
child = 2*parent+1;
}else {
break;
}
}
}
private void swap(int[] array,int i,int j) {
int tmp = array[i];
array[i] = array[j];
array[j] = tmp;
}
}
边栏推荐
- 快解析结合泛微OA
- How to run dist file on local computer
- shell脚本
- Concise Notes on Integrals - Types of Curve Integrals of the Second Kind
- C# 之 $ – 字符串内插
- Jetpack Compose 从入门到入门(八)
- Reflection tricks can boost your performance by N times
- echart图表清空上一次数据
- 国外资源加速下载器,代码全部开源
- Activating data potential Amazon cloud technology reshapes cloud storage "family bucket"
猜你喜欢
随机推荐
详解JVM垃圾回收
How to use Jmeter to carry out high concurrency in scenarios such as panic buying and seckill?
The FPGA based protocol 2: the I2C read and write E squared PROM
编译报错: undefined reference to `google::FlagRegisterer::FlagRegisterer解决方法
(BUG记录)No module named PIL
Jetpack Compose 从入门到入门(八)
积分专题笔记-与路径无关条件
02-课程发布
柱状图 直方图 条形图 的区别
Detailed description of iperf3 parameter options
Kotlin value class - value class
How to run dist file on local computer
MySQL Explain usage and parameter detailed explanation
leetcode 剑指 Offer 21. 调整数组顺序使奇数位于偶数前面
2022 Hangzhou Electric Multi-School 2nd Game
2022/07/29 学习笔记 (day19)异常处理
PyQt5-在窗口上绘制文本
日志导致线程Block的这些坑,你不得不防
PyQt5快速开发与实战 7.4 事件处理机制入门 and 7.5 窗口数据传递
方法的参数传递