优先级队列 c语言,使用最小堆使用优先级队列(c语言版本)
下面的例子來自Weiss的《數據結構與算法分析:c語言描述》,自己親自敲了一遍,跑了個demo,并將結果記錄下來。
binheap.h的頭文件聲明
//description: 使最小堆實現優先級隊列
//date: 2019-03-15
#ifndef __BINHEAP_H__
#define __BINHEAP_H__
typedef int ElementType;
struct HeapStruct {
int Capacity; //最大容量
int Size; //當前大小
ElementType *Elements; //元素數組
};
typedef struct HeapStruct *PriorityQueue;
PriorityQueue Initialize(int MaxElements);
void Destroy(PriorityQueue H);
void MakeEmpty(PriorityQueue H);
int IsEmpty(PriorityQueue H);
int IsFull(PriorityQueue H);
void Insert(ElementType X, PriorityQueue H);
ElementType DeleteMin(PriorityQueue H);
ElementType FindMin(PriorityQueue H);
#endif
binheap.c源碼文件
#include "binheap.h"
#include #include #define MinData (-32767)
#define MinPQSize (10)
PriorityQueue
Initialize(int MaxElements){
PriorityQueue H;
if(MaxElements < MinPQSize){
printf("Priority queue size is too small");
exit(-1);
}
H = malloc(sizeof(struct HeapStruct));
if(H == NULL){
printf("failed to alloc memory space for HeapStruct");
exit(-1);
}
/* allocate the array plus one extra for sentinel */
H->Elements = malloc( (MaxElements+1) * sizeof(ElementType));
if(H->Elements == NULL){
printf("failed to allocate memory for Elements array");
exit(-1);
}
H->Capacity = MaxElements;
H->Size = 0;
H->Elements[0] = MinData; //此處設置哨兵
return H;
}
void
Destroy(PriorityQueue H){
free(H->Elements);
free(H);
}
void
MakeEmpty(PriorityQueue H){
H->Size = 0;
}
void
Insert(ElementType X, PriorityQueue H){
int i;
if(IsFull(H)){
printf("Priority queue is full");
return;
}
//從尾部向頭部檢查
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)){
printf("FATAL: Priority queue is empty");
return H->Elements[0];
}
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];
printf("FATAL: Priority queue is Empty");
return H->Elements[0];
}
int
IsEmpty(PriorityQueue H){
return H->Size == 0;
}
int
IsFull(PriorityQueue H){
return H->Size == H->Capacity;
}
//=================================
int main(){
int i, NUM=30;
PriorityQueue pq = Initialize(NUM);
for(i=0; i
下面是運行圖示:
總結
以上是生活随笔為你收集整理的优先级队列 c语言,使用最小堆使用优先级队列(c语言版本)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 4GB内存电脑升级攻略:从选购到升级,省
- 下一篇: 内存频率选错了?主板不支持?怎么办?快来