Heap-based priority queue

Source: Internet
Author: User

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 &&amp ; 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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.