Heap的Array实现法

本文详细介绍了使用Array实现Heap的数据结构,包括大根堆的插入、删除操作。通过insert()方法插入元素并调用moveUp()确保堆性质,remove()方法移除根节点并用moveDown()调整新根。文章探讨了定义parent、left、right变量的时机,以及moveUp和moveDown操作中索引的使用,并给出了moveUp和moveDown的退出条件。在remove()方法中,需注意正确补充root并更新size。
摘要由CSDN通过智能技术生成
总论

Heap 逻辑上二叉树形状 物理上线性 array实现
这里做的是一个大根堆,涵盖方法有:
insert(): insert a new element to the heap
this invokes a help method called moveUp() cuz the inserted element may be larger than its parent, we need to move it up
初始建堆也就用insert()
remove(): remove the root of the heap
this invokes a help method called moveDown() cuz once the root is removed,
we use the rightmost element from the last level (logical view) to substitute the original root, and then this new root may not be the larger than its two children, so we need to move it down until it reaches its right position.
Def:
parent = (index - 1) / 2;
left = 2 * index + 1;
right = 2 * index + 2;
filling array from position 0

痛点

1.什么时候定义parent, left, right 这些变量?
何时用何时定,比如moveUp()用到parent所以在那里定义parent
2.moveUp 和 moveDown 是对 index进行操作
3.moveUp写法 出loop的条件 index <= 0
4.moveDown() 出Loop的条件 – index > size/2
5.粗心错,注意 remove() 补充root时要用array[size-1];然后size–; 当然也可以写 array[0]=array[–size];

代码
public class 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值