#include<iostream>
#include<stdlib.h>
using namespace std;
typedef struct HNode * Heap;
typedef int ElementType;
const int MaxSize = 1e3;
struct HNode {
ElementType * data;
int size;
int capacity;
};
typedef Heap MaxHeap;
//初始化以个
MaxHeap CreateHeap(int MaxSize) {
MaxHeap p = (MaxHeap)malloc(sizeof(struct HNode));
p->data = (ElementType *)malloc((MaxSize + 1) * sizeof(ElementType));
p->size = 0;
p->capacity = MaxSize;
p->data[0] = MaxSize;
return p;
}
bool IsFull(MaxHeap p) {
return p->size == p->capacity;
}
bool Insert(MaxHeap p, ElementType x) {
if (IsFull(p)) {
printf("最大堆已满\n");
return false;
}
//假设x插在末尾,上滤x
int i = ++p->size;
for (; p->data[i / 2] < x; i /= 2) {
p->data[i] = p->data[i / 2];
}
p->data[i] = x;
return true;
}
bool IsEmpty(MaxHeap p) {
return p->size == 0;
}
ElementType Delete(MaxHeap p) {
if (IsEmpty(p)) {
printf("最大堆已空\n");
return false;
}
//假设x插在头结点,下滤x
int parent, child;
ElementType max_item, x;
max_item = p->data[1];
x = p->data[p->size--];
//for循环有两个出口,要注意p->data[parent] = x不能只在break前赋值
for (parent = 1; parent * 2 <= p->size; parent = child) {
//child为孩子中较大的那个
child = parent * 2;
if ((child != p->size) && (p->data[child] < p->data[child + 1])) child++;
//找到合适的位置
if (x >= p->data[child]) break;
else {
p->data[parent] = p->data[child];
}
}
p->data[parent] = x;
return max_item;
}
void PercDown(MaxHeap p, int h) {
//调整以h为根节点的子树为最大堆
int parent, child;
ElementType x;
//x保存根节点的值,以实现交换
x = p->data[h];
//for循环有两个出口,要注意p->data[parent] = x不能只在break前赋值
for (parent = h; parent * 2 <= p->size; parent = child) {
child = parent * 2;
if ((child != p->size) && (p->data[child] < p->data[child + 1])) child++;
//child为孩子中较大的那个
if (x >= p->data[child]) break;
else {
p->data[parent] = p->data[child];
}
}
p->data[parent] = x;
}
void BuildHeap(MaxHeap p) {
for (int i = p->size / 2; i > 0; i--) PercDown(p, i);
}
void dfs(MaxHeap ptr, int p) {
if (p <= ptr->size) {
cout << ptr->data[p] << ' ';
if (p * 2 <= ptr->size) dfs(ptr, p * 2);
if (p * 2 + 1 <= ptr->size) dfs(ptr, p * 2 + 1);
}
}
int main() {
MaxHeap e = CreateHeap(12);
for (int i = 1; i <= e->capacity; i++) {
cin >> e->data[i];
}
e->size = e->capacity;
BuildHeap(e);
dfs(e, 1);
}
最大堆
最新推荐文章于 2021-12-01 18:54:14 发布