二叉堆C语言实现
2016-07-20 18:36
253 查看
二叉堆C语言实现
二叉堆是一种二叉树,其儿子的值一定不小于父亲的值,树的节点是按从上到下,从左到右紧凑排列的。
有两种操作:
push(x):将x插入二叉堆,并自动维护使二叉堆变得有序。
pop():取出顶部的值(最小值),并返回该值,同时维护二叉堆有序。
代码如下:
#include<stdio.h>
#define MAX_N 1000
int heap[MAX_N];
int sz = 0;
void push(int x)//插入堆的值
{
int now = sz++;//插入节点的编号
while(now > 0)
{
int f = (now - 1)/2;//父亲节点的编号
if(heap[f] <= x)break;//如果顺序未颠倒,则退出循环
heap[now] = heap[f];
now = f;
}
heap[now] = x;
}
int pop()
{
int res = heap[0];
int x = heap[--sz];//最末尾的节点
int i = 0;//从根节点开始操作
while(i * 2 + 1 < sz)
{
int lchild = 2 * i + 1;
int rchild = 2 * i + 2;
if(rchild < sz && heap[rchild] < heap[lchild])lchild = rchild;
if(heap[lchild] >= x) break;//如果x已经在lchild上层了,就可以停止了
heap[i] = heap[lchild];
i = lchild;
}
heap[i] = x;
return res;
}
int main()
{
printf("%d",pop());
return 0;
}
二叉堆是一种二叉树,其儿子的值一定不小于父亲的值,树的节点是按从上到下,从左到右紧凑排列的。
有两种操作:
push(x):将x插入二叉堆,并自动维护使二叉堆变得有序。
pop():取出顶部的值(最小值),并返回该值,同时维护二叉堆有序。
代码如下:
#include<stdio.h>
#define MAX_N 1000
int heap[MAX_N];
int sz = 0;
void push(int x)//插入堆的值
{
int now = sz++;//插入节点的编号
while(now > 0)
{
int f = (now - 1)/2;//父亲节点的编号
if(heap[f] <= x)break;//如果顺序未颠倒,则退出循环
heap[now] = heap[f];
now = f;
}
heap[now] = x;
}
int pop()
{
int res = heap[0];
int x = heap[--sz];//最末尾的节点
int i = 0;//从根节点开始操作
while(i * 2 + 1 < sz)
{
int lchild = 2 * i + 1;
int rchild = 2 * i + 2;
if(rchild < sz && heap[rchild] < heap[lchild])lchild = rchild;
if(heap[lchild] >= x) break;//如果x已经在lchild上层了,就可以停止了
heap[i] = heap[lchild];
i = lchild;
}
heap[i] = x;
return res;
}
int main()
{
printf("%d",pop());
return 0;
}
相关文章推荐
- Python实现二叉堆
- 二叉堆
- hihocoder:hiho一下第二十八周之二叉堆
- 堆排序实现
- c语言二叉堆《学习记录》poj3253
- 二叉堆
- 优先队列实现
- 二叉堆 build算法 c++ 数据结构与算法
- poj 3253 Fence Repair(哈夫曼树)
- ZOJ 2724 Windows Message Queue(二叉堆or优先队列)
- 优先队列二叉堆 C语言实现
- 数据结构(Java语言)——BinaryHeap简单实现
- 二叉堆(优先队列)
- 图论——Dijkstra+prim算法涉及到的优先队列(二叉堆)
- Huffman编码(Huffman树)
- 《数据结构与算法分析(c 描述)》—— 第六章笔记
- 二叉堆
- 【数据结构与算法】内部排序之三:堆排序(含完整源码)
- C++ 二叉堆头文件
- 数据结构之优先队列--二叉堆(Java实现)