二叉堆 build算法 c++ 数据结构与算法

数据结构与算法分析,C语言版(第140-141页)中构建堆,原理不再赘叙。

#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#include <math.h>


typedef int ElementType;
typedef struct HeapStruct *PriorityQueue;
struct HeapStruct {
int Capacity;
int Size;
ElementType *elements;
};


PriorityQueue Initialize(int MaxElements)

struct HeapStruct *H;
H = (struct HeapStruct *)malloc(sizeof(struct HeapStruct));
H->elements = (ElementType *)malloc(sizeof(ElementType)*(MaxElements+1));
H->elements[0] = NULL;
H->Capacity = MaxElements;
H->Size = 0;
return H;
}


//二叉堆的高度
int TreeHeight(PriorityQueue p)
{
int size = p->Size;
float height = (int)(log(float(size + 1))/log((float)2));
int _height = ceil(height);
return height;
}
//下滤
void PercolateDown(PriorityQueue p, int index)
{

int child;
for (int i = index; i <= p->Size; i = child)
{
child = i * 2;
if (child <= p->Size && (child + 1) <= p->Size&&p->elements[child] > p->elements[child + 1])
child++;
if (child <= p->Size&&p->elements[child] < p->elements[i])
{
ElementType temp = p->elements[i];
p->elements[i] = p->elements[child];
p->elements[child] = temp;
}
}
}
//构建堆
void BuildHead(PriorityQueue p)
{
int height = TreeHeight(p);
if (height == 1) return;
for (int i = (int)pow((float)2, height - 1)-1; i > 0; i--)
{
PercolateDown(p, i);
}


}
//数据顺序插入到堆中
void InsertHeap(PriorityQueue p, ElementType data)
{
if (p->Capacity != p->Size)
{
p->Size++;
p->elements[p->Size] = data;
}
}

void main()
{
//int a[] = { 10, 12, 1, 14, 6, 5, 8, 15, 3, 9, 7, 4, 11, 13, 2 };
int a[] = { 150, 80, 40, 30, 10, 70, 110, 100, 20, 90, 60, 50, 120};

PriorityQueue p = Initialize(sizeof(a)/sizeof(int));

int arraySize = sizeof(a) / sizeof(int);
for (int i = 0; i < arraySize; i++)
{
InsertHeap(p, a[i]);
}
BuildHead(p);
for (int i = 1; i <=p->Size; i++)
{
printf("第%d个元素为:%d\n", i, p->elements[i]);
}
system("pause");


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值