优先队列即二叉堆,实现如下:
#include <stdio.h>
#include <math.h>
#include <string.h>
#include <stdlib.h>
typedef int Element;
#define MAX_BINHEAP_LENGTH 10
struct BinaryHeap {
Element array[MAX_BINHEAP_LENGTH];
int length;
};
int Compare(const void* a, const void* b)
{
// minimul
return *(int*)a - *(int*)b;
// maximul
// return *(int*)b - *(int*)a;
}
void PercolateDown(struct BinaryHeap* heap, int hole)
{
int child;
Element temp = heap->array[hole];
for (; hole * 2 <= heap->length; hole = child) {
child = hole * 2;
if (child != heap->length && Compare(&(heap->array[child + 1]), &(heap->array[child])) < 0) {
child++;
}
if (Compare(&(heap->array[child]), &temp) < 0) {
heap->array[hole] = heap->array[child];
} else {
break;
}
}
heap->array[hole] = temp;
}
void BuildBinaryHeap(struct BinaryHeap* heap, Element* array, int length)
{
if (array == NULL || length == 0) {
memset(heap, 0, sizeof(struct BinaryHeap));
return;
}
for (int i = 0; i < length; i++) {
heap->array[i] = array[i];
heap->length = length;
}
for (int i = heap->length / 2; i > 0; i--) {
PercolateDown(heap, i);
}
}
int Empty(struct BinaryHeap* heap)
{
return heap->length == 0;
}
int Length(struct BinaryHeap* heap)
{
return heap->length;
}
void Insert(struct BinaryHeap* heap, Element elem)
{
int hole = ++(heap->length);
for (; hole > 1 && Compare(&elem, &(heap->array[hole / 2])) < 0; hole /= 2) {
heap->array[hole] = heap->array[hole / 2];
}
heap->array[hole] = elem;
}
// here is DeleteMinimum, if DeleteMaximum, change it!
void DeleteMinimum(struct BinaryHeap* heap)
{
if (heap->length == 0) {
return;
}
heap->array[1] = heap->array[heap->length--];
PercolateDown(heap, 1);
}
// here is GetMinimum, if GetMaximum, change it!
Element GetMinimum(struct BinaryHeap* heap)
{
return heap->array[1];
}
int main()
{
int array[8] = { 0, -13, 5, 23, -9, -2, 4, -6 };
struct BinaryHeap heap;
BuildBinaryHeap(&heap, array, 8);
while (!Empty(&heap)) {
Element elem = GetMinimum(&heap);
DeleteMinimum(&heap);
printf("%d
", elem);
}
return 0;
}