JAVA数据结构和算法(第十二章)学习笔记

DATE:2013-8-4
-------------------------------
一.堆的特点:
A)它是完全二叉树
B)一般情况下,用数组实现
C)堆中的每一节点都满足堆的条件(每一节点的关键字都大小或等于子节点的关键字)
D)相对于二叉搜索树,它是弱序的
E)节点索引下标:
》父节点下标:(index-1)/2
》左子节点:2*index + 1
》右子节点:2*index + 2

二、用堆实现的优先队列
1、前提
2、关键算法:
A)向上筛选(插入)

 int parent = (index-1) / 2;
Node bottom = heapArray[index];
while( index > 0 && //向上寻找合适的位置
heapArray[parent].getKey() < bottom.getKey() )
{
heapArray[index] = heapArray[parent]; // move it down
index = parent;
parent = (parent-1) / 2;
} // end while
heapArray[index] = bottom;//找到了合适的插入位置


B)向下筛选(移除、排序)

 int largerChild;
Node top = heapArray[index]; // save root
while(index < currentSize/2) // while node has at
{ // least one child,
int leftChild = 2*index+1;
int rightChild = leftChild+1;
// find larger child
if(rightChild < currentSize && // (rightChild exists?)
heapArray[leftChild].getKey() <
heapArray[rightChild].getKey())
largerChild = rightChild;
else
largerChild = leftChild;
// top >= largerChild?
if( top.getKey() >= heapArray[largerChild].getKey() )
break;
// shift child up
heapArray[index] = heapArray[largerChild];
index = largerChild; // go down
} // end while
heapArray[index] = top;


3、优缺点:相对于快速排序,略慢;但它对初始数据的分布不敏感
4、效率:O(N*logN)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值