您的位置:首页 > 编程语言 > C语言/C++

二叉堆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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  二叉堆