当前位置:网站首页>大根堆的创建(视频讲解)
大根堆的创建(视频讲解)
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;
}
}
边栏推荐
猜你喜欢
随机推荐
Detailed description of iperf3 parameter options
hcip06 ospf特殊区域综合实验
【 HMS core 】 【 】 the FAQ HMS Toolkit collection of typical questions 1
MySQL中使用IN 不会走索引分析以及解决办法
Unified exception handling causes ResponseBodyAdvice to fail
一个低级错误导致的诡异现象——走近科学能拍三集,(C语言)最简单的数组元素读取,不正确!?
Integral Special Notes-Three Formulas for Curve Area Integral
C# 之 $ – 字符串内插
微软 SQL 服务器被黑,带宽遭到破坏
Concise Notes on Integrals - Types of Curve Integrals of the Second Kind
【云原生】Kubernetes入门详细讲解
CSDN21天学习挑战赛
团队级敏捷真的没你想的那么简单
最长公共序列、串问题总结
The FPGA based protocol 2: the I2C read and write E squared PROM
XP电源维修fleXPower电源X7-2J2J2P-120018系列详解
【无标题】
Two solutions for Excel xlsx file not supported
积分专题笔记-曲线面积分三大公式
Liunx服务器安装SVN(安装包版)









