#include<cstdio>
#include<cstdlib>
#include<iostream>
#include<queue>
#include<stack>
#define OK 0
#define ERROR 1
using namespace std;
typedef int ElemType;
FILE *fp;
void InitFile()
{
bool e;
fopen_s(&fp, "data.txt", "r");
if (!fp) exit(ERROR);
return;
}
typedef bool Status;
/******
file input:
22 31 4 65 11 3 5 3 5
*******/
#define MAX_ELEMENTS 200
#define HEAP_FULL(n) (n==MAX_ELEMENTS-1)
#define HEAP_EMPTY(n) (!n)
ElemType heap[MAX_ELEMENTS];
int n;
Status insert_max_heap(ElemType item,ElemType &n)
{
int i;
if (HEAP_FULL(n)) exit(ERROR);
i = ++n;
while (i != 1 && item > heap[i / 2])
{
heap[i] = heap[i / 2];
i /= 2;
}
heap[i] = item;
return OK;
}
Status delete_max_heap(ElemType &item, ElemType &n)
{
if (HEAP_EMPTY(n))exit(ERROR);
item = heap[1];
heap[1] = heap[n--]; heap[n + 1] = item;
int parent, child;
parent = 1;
// child = 2;
int temp=1;
int t;
while (1)
{
child = parent * 2;
if (child <= n)
{
temp = heap[parent] < heap[child] ? child : parent;
}
if (child + 1 <= n)
{
temp=heap[temp]>heap[child + 1] ? temp : child + 1;
}
if (temp == parent) break;
else {
t = heap[temp]; heap[temp] = heap[parent]; heap[parent] = t;
parent = temp;
}
}
return OK;
}
//by zhaoyang 2014.4.19
int main()
{
InitFile();
init heap
n = 0;
int t;
for (int i = 11; i < 20; i++)
insert_max_heap(i, n);
for (int i = 11; i < 20; i++)
{
delete_max_heap(t, n);
printf("%d ", t);
}
putchar(10);
fclose(fp);
return 0;
}
17.完全二叉树 构建 最大堆 元素的添加和删除(堆排)
最新推荐文章于 2023-05-06 16:36:56 发布