The source code is as follows
#include <stdio.h> #include <stdlib.h>typedef struct Item *node;struct item{int data;char c;}; static item *pq;static int N; void swap (Item &a,item &b) {struct Item t = a;a = B;b = t;} Bottom-up heap the key value of the full binary tree parent node is greater than or equal to the child node key value void Fixup (Item a[],int k) {//k represents the location that destroys heap rules O (NLGN) while (k>1 && A[k/2].data & Lt A[k].data) {swap (A[K],A[K/2]); k = K/2;}} Top-down heap void Fixdown (Item a[],int k,int N) {//k represents the location that destroys heap rule keywords, n is the size of the heap int J; while (2*k<=n) {j = 2*k;if (J<n && ; A[j].data<a[j+1].data) j + +; Handle the case where the K node has only one child node if (a[k].data>=a[j].data) Break;swap (A[k],a[j]); k = j;}} void Pqinit (int maxn) {PQ = (node) malloc ((maxn+1) *sizeof (node)); N = 0;} int Pqempty () {return n==0;} void Pqinsert (Item v) {Pq[++n] = V; PQ[0] is not used and can be used as an observation post in some implementations. Fixup (pq,n);} Item Pqdelmax () {swap (pq[1],pq[n]); Fixdown (pq,1,n-1); return pq[n--];} Main () {pqinit (+); struct Item a[8] = {{0, ' 0 '},{7, ' C '},{95, ' C '},{12, ' C '},{96, ' C '},{76, ' C '},{36, ' C '},{46, ' C '}};int J; for (j=1;j<=7;j++) Pqinsert (A[j]);p rintf ("Rawinto a heap of ordered complete binary tree structure \ n "); for (j=0;j<7;j++) printf ("%d\n", Pq[j+1].data);p rintf ("The maximum value of the priority queue is gradually removed \ n"), for (j=0;j<7;j++) printf ("%d\n", Pqdelmax (). data);}
Run results
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Heap-based priority queue