Priority Queue (heap)-Data structure (C language Implementation)

Source: Internet
Author: User
Tags int size

Data structure and algorithm analysis

Priority Queue Model
    • Insert (insert) = = Enqueue (queue)
    • Deletemin (delete the smallest) = = Dequeue (out of the team)
Basic implementation
    • Simple linked list: Insert in the table header and traverse the list to remove the minimum element

      Time is costly.

    • Binary search Tree

      Binary lookup tree supports many unwanted operations, which are not worth the hassle of implementing
      Most suitable: two fork pile


Two kinds of properties of binary pile Structural
    • Fully binary tree: Completely fills the bottom, and the bottom is filled from left to right
    • The height of the complete binary tree is
  log N
    • Distributions are very regular and can be implemented in arrays

Left son = 2i

Right son = 2i + 1

Sequence of the heap
    • The minimum element of the tree should be on the root node
    • Each node x,x the father's keyword should be less than or equal to the X keyword
Realize Declaration of the Priority queue
struct HeapStrcut ;typedef struct HeapStruct *PriorityQueue ;PriorityQueue Intialize(int MaxElement) ;void Destory(PriorityQueue H) ;void MakeEmpty(PriorityQueue H) ;void Insert(ElementType X, PriorityQueue H) ;ElementType DeleteMin(PriotityQueue H) ;ElementType Find(PritityQueue H) ;int IsEmpty(PriorityQueue H) ;int IsFull(PriorityQueue H) ;srtuct HeapStruct{    int Capacity ;    int Size l    ElementType *Elements ;}
Initialization
PriorityQueue Intialize(int MaxElement){    PriorityQueue H ;    H->Elements = malloc((MaxElement + 1) * sizeof(ElementType) ;    if(H->Elements == NULL)        FatalError("内存不足");    H->Capacity = MaxElement ;     H->Size = 0;    H->Elements[0] = MinData ;//在根节点赋一个绝对的小的值        return H ;}
Insert operation

Upper Filter

void Insert(ElementType X, PriorityQueue H){    int i ;    if(IsFull(H))        Error("堆满") ;        for(i = ++H->Size;H->Elements[i/2] > X;i/2)        H->Elenemts[i] = H->Elements[i/2] ;    H->Elements[i] = X ;        return H ;}
Delete function

Down filter

First to get the last element, and the current is deleted after the remaining hole of the smallest son comparison, if the son of small change to the hole, continue to filter, in turn, the last element will be placed at the end of the hole filter

ElementType Insert(PriorityQueue H){    int i,Child ;    ElementType MinElement,LastElement ;        if(IsEmpty(H))    {        Error("堆为空") ;        return H->Elements[0] ;    }    MinElement = H->Elements[1];    LastElement = H->Elements[H->Size--] ;    for(i = 1; i * 2 <= H->Size;i = Child)    {        Child = i * 2;        if(Child != H->Size && H->Element[Child] > H->Elements[Child + 1])            Child ++ ;                    if(LastElement > H->Elements[Child)            H->Elements[i] = H->Elements[Child] ;        else break ;    }    H->Elements[i] = LastElement ;        return MinElenemt;}
Left-side heap properties

Efficient support for merge operations

The only difference between a two-fork tree is that the left-hand heap is not an ideal balance

For each node in the heap X, the left son's 0 path long NPL is greater than the right son's 0 path long NPL

- 零路径长(NPL):从该节点到一个没有两个儿子的节点的最短路径长
Type declarations for Zuo
PriorityQueue Intailize(void) ;ElementType FindMin(PriorityQueue H) ;int IsEmpty(PriorityQueue H) ;PriorityQueue Merge(PriorityQueue H1,PriorityQueue H2) ;#define Insert(X,H) (H = Insert1(X,H)) ; //为了兼容二叉堆PriorityQueue Insert1(ElementType, PriorityQueue H) ;PriorityQueue DeleteMin(PriorityQueue H) ;sturct TreeNode{    ElementType Element ;    PriorityQueue Left ;    PriorityQueue Right ;    int Npl ;}
Merge operation

Driver Program

PriorityQueue Merge(PriorityQueue H1,PriorityQueue H2){    if(H1 == NULL)        return H2 ;    eles if(H2 == NULL)        return H1 ;    else if(H1->Element > H2->Element)        return Merge1(H1,H2) ;    else        return Merge1(H1S,H2) ;}

Actual operation

PriorityQueue Merge1(PriortyQueue H1,PriorityQueue H2){    if(H1->Left == NULL)        H1->Left = H2 ;    else    {        H2->Right = Merge1(H1->Right,H2) ;        if(H1->Left->Npl < H1->Right->Npl)            SwapChildren(H1) ;        H1->Npl = H1->Right->Npl + 1;    }        return H1 ;}
Insert operation
PriorityQueue Insert(ElementType X,PriorityQueue H){    PriorityQueue SinglNode ;    SinglNode = malloc(sizeof(TreeNode)) ;    if(SinglNode == NULL)        FatalError("内存不足") ;    else    {        SingleNode->Element = X ;        SingleNode->Npl = 0 ;        SingleNode->Left = SingleNode->Right = NULL ;        Merge(SingleNode,H) ;    }    return H ;}
Delete operation
PriorityQueue DeleteMin1(PriorityQueue H){    PriorityQueue LeftHeap,RightHeap ;        if(IsEmpty(H))        FatalError("队列为空") ;    else    {        LeftHeap = H1->Left ;        RightHeap = H1->Right ;        free(H) ;        Merge(LeftHeap,RightHeap) ;    }}
Two-item queue structure
    • The two-item queue is a collection of heap-sequence trees called forest
    • Each tree in the heap is a constrained tree, called a two-item tree
    • Two trees with a height of K have a two tree Bk-1 attached to the root of another two tree Bk-1
Implementation of the two-item queue

Two items queue will be an array of two trees

Each node of the two-item tree contains data, the first son and a brother

Two type declaration for a queue `
typedef struct BinNode *Position ;typedef struct Collection *BinQueue ;struct BinNode{    ElementType Element ;    Position LeftChild ;    Position NextBiling ;}typedef Position BinTree ;struct Collection{    int CurrentSize ;    BinTree TheTrees[MaxTree] ;}
Merge operation

Merge two two two-item trees of the same size

BinTree ConbineTrees(BinTree T1,BinTree T2){    if(T1->Element > T2->Element)        return CombineTree(T2,T1) ;    T2->NextBling = T1->LeftChild ;    T1->LeftChild = T2 ;        return T1 ;}

Merge two priority queues

Binqueue Merge (binqueue h1,binqueue H2) {bintree t1,t2,carry = NULL;    int I, J;        if (h1->currentsize + h2->currentsize > Capacity) Error ("Too large after merging");    H1->currentsize + = H2->currentsize;        for (i = 0;j = 1;j <= h1->currentsize; i++,j *= 2) {T1 = H1->thetree[i];                T2 = H2->thetree[i]; Switch (!! T1 + 2 *!! T2 + 4 *!!                Carry) {case 0://empty tree case 1:break;//Only H1 Case 2:                H1->thetree[i] = T2 h2->thetree[i] = NULL;            break;                Case 4:h1->thetree[i] = Carry;            Carry = NULL;                Case 3://h1 and H2 Carry = Combinetrees (T1,T2);                H1->thetree[i] = h1->thetree[i] = NULL;            break;                Case 5://H1 and carry carry = Conbinetrees (T1,carry);            H1->thetrees[i] = NULL; CasE 6:carry = conbinetrees (T2,carry);            H2->thetrees[i] = NULL;                Case 7://both have h1->thetree[i] = Carry;                Carry = Combinetrees (T1,T2);                H2->thetrees[i] = NULL;                        break; }} return H1;}
Summarize

Priority queues can be implemented with a binary stack, which is simple and fast

But considering the merge operation, the left-hand heap and the two-time queue are extended

Priority Queue (heap)-Data structure (C language Implementation)

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.