17.完全二叉树 构建 最大堆 元素的添加和删除(堆排)


#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;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值