完全二叉树叫做堆。

完全二叉树就是最后一个节点之前不允许有不满的节点,就是不允许有空洞。

可以使用数组来做完全二叉树(堆)。

堆分为大顶堆和小顶堆。大顶堆就是根节点上的数字是最大的,小顶堆就是根节点上的数字是最小的堆。

在堆里面的操作包括两种:插入新的节点和删除根节点。

插入新节点的操作时向上渗透。删除根节点的操作是向下渗透。

插入新节点时,把新的节点插入到最后一个位置,然后慢慢向上渗透(和父辈交换)。删除根节点时,把最后一个节点放到根节点上,然后再慢慢向下渗透(和子代交换)。

下面使用Java写一个大顶堆。

package Heap;

public class MaxHeap {
private int[] heapArray;
private int maxSize;
private int currentSize;
/*构造函数*/
public MaxHeap(int mx) throws Exception {
if(mx < 1) throw new Exception("max size must be >=1");
maxSize = mx;
currentSize = 0;
heapArray = new int[maxSize];
}
/*向上渗透,index为下标*/
private void trickleUp(int index){
int parent = (index - 1) / 2;
int bottom = heapArray[index];
while(index>0 && heapArray[parent]<bottom){
heapArray[index] = heapArray[parent];
index = parent;
parent = (parent - 1) / 2;
}
heapArray[index] = bottom;
}
/*向下渗透*/
private void trickleDown(int index){
int largerChild;
int top = heapArray[index];
while(index < currentSize / 2){
int leftChild = 2 * index + 1;
int rightChild = 2 * index + 2;
if(rightChild<currentSize && heapArray[leftChild]<heapArray[rightChild])
largerChild = rightChild;
else
largerChild = leftChild;
if(top >= heapArray[largerChild])
break;
heapArray[index] = heapArray[largerChild];
index = largerChild;
}
heapArray[index] = top;
}
public boolean IsEmpty(){
return currentSize == 0;
}
public void Push(int num) throws Exception{
if(currentSize == maxSize) throw new Exception("MaxHeap id full");
heapArray[currentSize] = num;
trickleUp(currentSize);
currentSize++;
}
public int Top(){
return heapArray[0];
}
public void Pop(){
heapArray[0]=heapArray[--currentSize];
trickleDown(0);
}
public static void main(String[] args) throws Exception {
System.out.println("测试大顶堆");
MaxHeap maxHeap = new MaxHeap(100);
System.out.println(maxHeap.IsEmpty());
maxHeap.Push(20);
maxHeap.Push(30);
maxHeap.Push(40);
System.out.println(maxHeap.Top());
maxHeap.Push(90);
maxHeap.Push(80);
maxHeap.Push(70);
System.out.println(maxHeap.Top());
maxHeap.Pop();
System.out.println(maxHeap.Top());
maxHeap.Pop();
System.out.println(maxHeap.Top());
maxHeap.Pop();
System.out.println(maxHeap.Top());
}
}

堆排序就是迭代弹出栈顶元素。

堆排序的时间复杂度是O(nlogn).

最新文章

  1. PHP框架模板原理
  2. Binary Tree Maximum Path Sum
  3. c#中获取数组的行列个数的方法
  4. lucene字典实现原理
  5. javascript的三个组成部分
  6. 【POJ 1035】Spell checker
  7. Matlab动态数组实现
  8. 【自动化测试】Xpath学习
  9. VC2008如何生成及使用DLL(完整版)
  10. Spring注入静态变量(转)
  11. HihoCoder
  12. jquery中的事件与应用
  13. DevOps工程师到底做些什么?
  14. poj2054 Color a Tree
  15. 即时通讯协议之XMPP
  16. 潭州课堂25班:Ph201805201 tornado 项目 第四课 增加用户注册登录(课堂笔记)
  17. python del 方法的使用
  18. HTML5扩展之微数据与丰富网页摘要——张鑫旭
  19. 【vue知识点】1)vue生命周期
  20. 【CF767C】Garland

热门文章

  1. python的编解码问题
  2. Genymotion的使用 -- A Faster Android Emulator
  3. 总结:实体类和(XML或二进制)之间相互转(序列化和反序列化)
  4. 基于SSL的WCF传输安全
  5. WPF中ToolTip的自定义
  6. iOS下拉图片放大
  7. 2015.2.27 UltraEdit中显示XML结构
  8. 在Google Colab中导入一个本地模块或.py文件
  9. python window使用paramiko简单监控数据指标数据采集
  10. select 动态添加option函数