使用最小堆使用优先级队列(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 <stdio.h>
#include <stdlib.h>#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];elsebreak;}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<NUM; i++)Insert(i, pq);while(!IsEmpty(pq)){i = DeleteMin(pq);printf("%d\n", i);}Destroy(pq);return 0;
}
下面是運行圖示:
總結
以上是生活随笔為你收集整理的使用最小堆使用优先级队列(c语言版本)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 十种经典排序算法精粹(c语言版本)
- 下一篇: 删除单链表中的重复节点(c语言版本)