1.优先队列中,元素被赋予优先级。当访问元素时,具有最高优先级的元素最先删除。优先队列具有最高级先出 (first in, largest out)的行为特征。
2.用堆实现的优先队列中,最大堆只能对应最大优先队列,最小堆则是对应最小优先队列。
堆的实现,戳这里
PriorityQueue.h
#define N 1000
typedef int Datatype;
typedef struct PriorityQueue
{
Datatype a[N];
size_t size;
}PriorityQueue;
void PriorityQueuePush(PriorityQueue* q,Datatype data);
void PriorityQueueInit(PriorityQueue* q);
void PriorityQueuePop(PriorityQueue* q);
Datatype PriorityQueueTop(PriorityQueue* q);
size_t PriorityQueueEmpty(PriorityQueue* q);
size_t PriorityQueueSize(PriorityQueue* q);
PriorityQueue.c
void PriorityQueueInit(PriorityQueue* q)
{
assert(q);
q->size = 0;
memset(q->a, 0, sizeof(Datatype)*N);
}
void AdjustUp(Datatype* a,size_t size,int child)//向上调整
{
int parent = (child - 1) >> 1;
while (child > 0)
{
if (a[child] > a[parent] && (child < size))
{
Datatype tmp = a[child];
a[child] = a[parent];
a[parent] = tmp;
}
else
break;
child = parent;
parent = (child - 1) >> 1;
}
}
void PriorityQueuePush(PriorityQueue* q, Datatype data)//插入
{
assert(q);
if (N == q->size)
{
printf("PriorityQueue is FULL\n");
return;
}
q->a[q->size] = data;
q->size++;
/*for (int i = 0; i < q->size; i++)
{
AdjustDown(q->a, q->size, i);
}*/
AdjustUp(q->a,q->size,q->size-1);//优先队列要有优先顺序,在数组(堆底)插入元素,调用向上调整,调整整个堆结构
}
void PriorityQueuePop(PriorityQueue* q)//删除
{
assert(q);
if (0 == q->size)
{
printf("PriorityQueue is NULL\n");
return;
}
/*size_t begin = 1;//时间复杂度O(n)
while (begin < q->size)
{
q->a[begin - 1] = q->a[begin];
++begin;
}
q->size--;*/
//将最后一个元素和第一个元素交换,向下调整整个堆结构
q->a[0] = q->a[q->size - 1];//时间复杂度O(log n)
AdjustDown(q->a, q->size, 0);
q->size--;
}
Datatype PriorityQueueTop(PriorityQueue* q)
{
return q->a[0];
}
size_t PriorityQueueEmpty(PriorityQueue* q)
{
if (0 == q->size)
return 0;
}
size_t PriorityQueueSize(PriorityQueue* q)
{
assert(q);
int count = 0;
while (q->size--)
{
count++;
}
return count;
}
void TestPriorityQueue()
{
PriorityQueue q;
PriorityQueueInit(&q);
PriorityQueuePush(&q, 5);
PriorityQueuePush(&q, 2);
PriorityQueuePush(&q, 3);
PriorityQueuePush(&q, 18);
PriorityQueuePush(&q, 0);
PriorityQueuePush(&q, 23);
PriorityQueuePush(&q, 7);
PriorityQueuePush(&q, 6);
PriorityQueuePush(&q, 1);
PriorityQueuePush(&q, 4);
while (PriorityQueueEmpty(&q) != 0)
{
printf("%d ", PriorityQueueTop(&q));
PriorityQueuePop(&q);
}
printf("\n");
}