It is common for priority queues to be implemented by a two-fork heap.
Below I call the heap of two forks.
The heap is a fully filled two-fork tree, a two-tree height of H 2h to 2h+1-1 nodes. This means that the full binary tree is high-time log N.
Because a fully binary tree is very regular, all it can be represented by an array, without the need for pointers
For this tree, we can say so.
For an element of any position I on the array, whose left son is on position 2 I, the right son is in the cell after the left son (2 i + 1), and its father is in position (I/2).
1 #ifndef _binheap_h2 3 structheapstruct;4 5typedefintElementType6 7typedefstructHeapstruct *Priorityqueue;8 9Priorityqueue Initialize (intmaxelenments);Ten One voidDestroy (Priorityqueue H); A - voidmakeempty (Priorityqueue H); - the voidInsert (ElementType x,priorityqueue H); - - ElementType deletemin (Priorityqueue H); - + ElementType Find (Priorityqueue H); - + intIsEmpty (Priorityqueue H); A at intIs full (Priorityqueue H); - - - #endif //_binheap_h - - structheapstruct{ in intcapacity; - intSize; toElementType *Elements; +};
1 //Initializing a heap2Priorityqueue Initialize (intmaxelements)3 {4 priorityqueue H;5 6 if(Maxelements <minpqsize)7Error ("Priority Queue size is too small");8 9H = malloc (sizeof(structheapstruct));//h equals heapstruct memory size, malloc is requesting a memory space from the system. Ten if(H = =NULL) OneFatelerror ("Out of space!!!"); AH->elements = malloc ((maxelements+1)*sizeof(ElementType));//Request a memory space, and then you can manipulate the elements like an array. - - the if(H->elements = =NULL) -FatalError ("Out of space!!!");//h has no child nodes. - -H->capacity =maxelements; +H->size =0; -h->elements[0] =MinDate + A returnH; at}
1 //inserting elements2 3 voidInsert (ElementType X, Priorityqueue H)4 {5 inti;6 if(Isfull (H))7 {8Error ("Priority Queue was full");9 return ;Ten } One for(inti = ++h->size; h->elements[i/2]>x;i/=2)//use bubbling, one to go up. AH->elements[i] = h->elements[i/2];//if it's smaller than its father's node, then bubble up. -H->elements[i] =X; -}
1 //Delete Minimum value2 3 ElementType deletemin (priorityqueue H)4 {5 intI,child;6 Elementype minelement, lastelement;7 8 if(IsEmpty (H))9 {TenError ("Priority Queue is empty"); One returnh->elements[0 ]; A } -Minelement = h->elements[1 ]; -Lastelement = h->elements[h->size-- ]; the - for(i =1I2<= h->size; i = child)//The minimum value of each child node is raised to the original parent node. - { -Child = i *2; + if(Child! = h->size && h->elements[child+1 ] -< h->elements[Child]) +child++; A at if(Lastelement > h->elements[Child]) -H->elements[i] = h->elements[Child]; - Else - Break; - } -h->elements[I] =lastelement; in returnminelement; - to}
Priority queue (Heap implementation)