您的位置:首页 > 理论基础 > 数据结构算法

C源码@数据结构与算法->PriorityQueues

2015-08-22 16:39 417 查看
/*
 * binheap.cpp
 */
#include <stdlib.h>
#include "fatal.h"
#include "binheap.h"

#define MinPQSize (10)
#define MinData (-32767)

struct HeapStruct
{
	int Capacity;
	int Size;
	ElementType *Elements;
};

PriorityQueue Initialize(int MaxElements)
{
	PriorityQueue H;

	if (MaxElements < MinPQSize)
	{
		FatalError("Priority queue size is too small!");
	}

	H = (PriorityQueue)malloc(sizeof(struct HeapStruct));
	if (H == NULL)
	{
		FatalError("Out of space!");
	}

	/* Allocate the array plus one extra for sentinel */
	H->Elements = (ElementType *)malloc(sizeof(ElementType) 
		* (MaxElements + 1));
	if (H->Elements == NULL)
	{
		FatalError("Out of space!");
	}

	H->Capacity = MaxElements;
	H->Size = 0;
	H->Elements[0] = MinData;

	return H;
}

void MakeEmpty(PriorityQueue H)
{
	H->Size = 0;
}

int IsEmpty(PriorityQueue H)
{
	return H->Size == 0;
}

int IsFull(PriorityQueue H)
{
	return H->Size == H->Capacity;
}

/*
 * H->Elements[0] is a sentinel.
 *
 * Heap Order Proprety: 
 * In a heap, for every node x, the key in the parent of X is smaller than
 * (or equal to) the key in X, with the exception of the root(which has no parent).
 */
void Insert(ElementType X, PriorityQueue H)
{
	int i;

	if (IsFull(H))
	{
		FatalError("Priority queue is full!");
	}

	for (i = ++H->Size; H->Elements[i / 2] > X; i /= 2)
	{
		H->Elements[i] = H->Elements[i / 2];
	}
	H->Elements[i] = X;
}

ElementType DeleteMin(PriorityQueue H)
{
	int i, Child;
	ElementType MinElement, LastElement;

	if (IsEmpty(H))
	{
		FatalError("Priority queue is empty!");
	}
	MinElement = H->Elements[1];
	LastElement = H->Elements[H->Size--];

	for (i = 1; i * 2 <= H->Size; i = Child)
	{
		/* Find smaller child */
		Child = i * 2;
		if (Child != H->Size
			&& H->Elements[Child + 1] < H->Elements[Child])
		{
			Child++;
		}

		/* Percolate one level */
		if (LastElement > H->Elements[Child])
		{
			H->Elements[i] = H->Elements[Child];
		}
		else
		{
			break;
		}
	}
	H->Elements[i] = LastElement;

	return MinElement;
}

ElementType FindMin(PriorityQueue H)
{
	if (!IsEmpty(H))
	{
		return H->Elements[1];
	}
	else
	{
		FatalError("Priority queue is empty!");
		return -1;		/* Just for avoid warning */
	}
}

void Destroy(PriorityQueue H)
{
	free(H->Elements);
	free(H);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: