优先权队列------树-完全二叉树-最小堆-优先权队列

#include<stdio.h>
#include<stdlib.h>
#define MaxSize 101
#define T int
typedef struct minheap {
	int Size;
	T Elements[MaxSize];
}MinHeap;
typedef MinHeap PQueue;
//向下调整,针对位于上层的数值大的元素,按照完全二叉树下沉
void AdjustDown(T heap[], int r, int n);
//构建堆
void CreateHeap(MinHeap* hp);
//向上调整,针对位于底层的数值小的元素,按照完全二叉树上浮
void AdjustUp(T heap[], int n);
//优先权队列添加元素的函数
void Append(PQueue* pq, T x);
//判断是否为满
int IsFull(PQueue* pq);
//判断是否为空
int IsEmpty(PQueue* pq);
//优先权队列删除完全二叉树根元素的函数,也就是删除优先权队列最高有限权的元素,仅针对最小堆而言。
void Serve(PQueue* pq);
void main() {
	int i;
	PQueue* qq = (PQueue*)malloc(sizeof(PQueue));
	qq->Size = 8;
	//T array[MaxSize]= { 0, 61,28,81,43,36,47,83,5 };
	qq->Elements[0] = 0;
	qq->Elements[1] = 61;
	qq->Elements[2] = 28;
	qq->Elements[3] = 81;
	qq->Elements[4] = 43;
	qq->Elements[5] = 36;
	qq->Elements[6] = 47;
	qq->Elements[7] = 83;
	qq->Elements[8] = 5;
	CreateHeap(qq);
	for (i = 1; i <= qq->Size; i++) {
		printf("%d ", qq->Elements[i]);
	}
	Append(qq, 1);
	printf("\n");
	for (i = 1; i <= qq->Size; i++) {
		printf("%d ", qq->Elements[i]);
	}
	printf("\n");
	Serve(qq);
	for (i = 1; i <= qq->Size; i++) {
		printf("%d ", qq->Elements[i]);
	}
	printf("\n");
	Serve(qq);
	for (i = 1; i <= qq->Size; i++) {
		printf("%d ", qq->Elements[i]);
	}
	printf("\n");
}
void CreateHeap(PQueue* hp) {
	int i, n = hp->Size;
	for (i = n / 2; i > 0; i--) {
		AdjustDown(hp->Elements, i, n);
	}
}
void AdjustDown(T heap[], int r, int n) {
	int child = 2 * r;
	T temp = heap[r];
	while (child <= n)
	{
		if (child<n && heap[child]>heap[child + 1]) {
			child++;
		}
		if (temp <= heap[child]) {
			break;
		}
		heap[child / 2] = heap[child];
		child *= 2;
	}
	heap[child / 2] = temp;
}
void AdjustUp(T heap[], int n) {
	int i = n; T temp = heap[i];
	while (i != 1 && temp < heap[i / 2]) {
		heap[i] = heap[i / 2];
		i /= 2;
	}
	heap[i] = temp;
}
int IsFull(PQueue* pq) {
	if (pq->Size == MaxSize) {
		return 1;
	}
	return 0;
}
int IsEmpty(PQueue* pq) {
	if (pq->Size == 0) {
		return 1;
	}
	return 0;
}
void Append(PQueue* pq, T x) {
	if (IsFull(pq)) {
		printf("优先权队列满了!\n");
	}
	else {
		pq->Elements[++pq->Size] = x;
		AdjustUp(pq->Elements, pq->Size);
	}
}
void Serve(PQueue* pq) {
	if (IsEmpty(pq)) {
		printf("优先权队列空了!\n");
	}
	else {
		pq->Elements[1] = pq->Elements[pq->Size--];
		AdjustDown(pq->Elements, 1, pq->Size);
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值