当前位置:网站首页>大根堆的创建(视频讲解)
大根堆的创建(视频讲解)
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;
}
}
边栏推荐
猜你喜欢

Explain the problem of change exchange in simple terms - the shell of the backpack problem

Using IN in MySQL will not go through index analysis and solutions

STM8L_库函数-模板搭建

深入浅出零钱兑换问题——背包问题的套壳

Matplotlib--绘图标记

如何避免CMDB沦为数据孤岛?

The FPGA based protocol 2: the I2C read and write E squared PROM

MySQL之COUNT性能到底如何?

Access to display the data

leetcode 剑指 Offer 25. 合并两个排序的链表
随机推荐
积分简明笔记-第一类曲线积分的类型
快解析结合任我行crm
leetcode 剑指 Offer 10- I. 斐波那契数列
2022/07/29 学习笔记 (day19)异常处理
Shell系统学习之数组
九九乘法表
图像分析:投影曲线的波峰查找
延迟队列MQ
(BUG记录)No module named PIL
【深度学习】(问题记录)<对一个变量求梯度得到什么>-线性回归-小批量随机梯度下降
Integral Special Notes - Definition of Integral
How to use Jmeter to carry out high concurrency in scenarios such as panic buying and seckill?
团队级敏捷真的没你想的那么简单
Unity performance analysis Unity Profile performance analysis tool
2022 Hangzhou Electric Multi-School 1st Game
深入浅出零钱兑换问题——背包问题的套壳
leetcode 剑指 Offer 21. 调整数组顺序使奇数位于偶数前面
Kotlin 值类 - value class
Taosi TDengine 2.6+ optimization parameters
Use the R language to read the csv file into a data frame, and then view the properties of each column.