您的位置:首页 > 其它

二叉堆

2015-09-20 15:41 218 查看
    二叉堆是一种富有特色的数据结构,可用数组简便实现。明显的规律,eg:L_child=parent * 2  ,  R_child=parent * 2  + 1;

  

#include <stdio.h>
#define N 100
int heap
,size=0;
void push(int x)
{
int i=size++;
while(i>0)
{
int j=(i-1)/2;
if(heap[j]<=x) break;
heap[i]=heap[j];
i=j;
}
heap[i]=x;
}

int pop()
{
int res=heap[0],t=heap[--size];
int i=0;
while(i*2+1<size)
{
int j=i*2+1;
if(j+1<size&&heap[j+1]<heap[j])
j++;
if(heap[j]>=t) break;
heap[i]=heap[j];
i=j;
}
heap[i]=t;
return res;
}

int main()
{
int x;
while(1)
{
scanf("%d",&x);
if(x==-1) break;
push(x);
}
while(size)
printf("%d%c",pop(),size==1? '\n':' ');
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: