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;
}