Data structure-two fork heap (c description)

Source: Internet
Author: User
Tags insert int size

1. The main storage structure

struct HeapStruct
{
  int Capacity;//最大容量
  int Size;//当前容量
  ElementType *Elements;//数组入口地址
};
typedef struct HeapStruct *PriorityQueue;

The structure body heapstruct is actually an array, the bottom implementation of the binary heap is a complete binary tree, so it is convenient to use the array implementation.

An important property of a complete binary tree is the explicit placement of a parent-child relationship:

The rank of node V is set I (the rank of the root node is 0), then

If V has Zoozi, Zoozi's rank =2 * i + 1;

If V has right son, the right son's rank =2 * i + 2;

If V has a father, the rank of the father = (i-1)/2;

2. Main heap operation

In order to maintain the heap order, the main involved in the heap operations are two, that is, insert and delete nodes.

2.1 Insert Node-O (Logn)

The algorithm for inserting nodes is,

1. The new node is inserted at the end of the heap.

2. Cycle-Compare the node to its parent node;

2.1 If the node < parent node, then exchange it;

2.2 Otherwise, stop with the current position, that is, the insertion position.

The process of this cycle is the filtration process.

This sets a dummy node element[0], where a minimum is placed so that the loop terminates, which avoids adding a single judgment statement to the loop body. Now the heap top is element[1] and the parent-child position relationship:

The rank of node V is set I (the rank of the root node is 1), then

If V has Zoozi, Zoozi's rank =2 * i;

If V has right son, the right son's rank =2 * i + 1;

If V has a father, father's rank =i/2;

/* H->Element[ 0 ] is a sentinel */
void Insert( ElementType X, PriorityQueue H )
{
    int i;
    if( IsFull( H ) )
    {
        Error( "Priority queue is full" );
        return;
    }
    for( i = ++H->Size; H->Elements[ i / 2 ] > X; i /= 2 )
        H->Elements[ i ] = H->Elements[ i / 2 ];
    H->Elements[ i ] = X;
}

Related Article

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.