C ++ Heap Structure (Array Implementation)

Source: Internet
Author: User

To say the maximum heap and the minimum heap, you must first know the decision tree and the minimum tree.

A tree whose values are greater than (less than) or equal to the values of its subnodes (if any) is called the maximum (minimum) tree.

The maximum heap (minimum heap) is the maximum (minimum) full tree.

Because the heap is a Complete Binary Tree, you can use a formula to describe the heap structure effectively using a one-dimensional array.

The nature of Binary Trees:

If the nodes of a Complete Binary Tree with n knots are numbered by sequence (from Layer 1 to layer [log2n], the nodes are rounded down to layer + 1, from left to right ), for any node I (1 ≤ I ≤ n), there are:

(1) If I = 1, node I has no parent and is the root of a binary tree. If I> 1, the parent node [I/2] is rounded down.

(2) If 2i> n, node I is a leaf node without left child. Otherwise, the left child is node 2i.

(3) If 2i + 1> n, node I has no right child; otherwise, the right child is node 2i + 1.

In this way, the heap node can be moved to its parent node or one of its subnodes.

The operations in heap are mainly insert, delete, and initialize.

The maximum heap is discussed below.

Insert data in the largest heap. For example, insert data in the largest heap on the left. The structure of the inserted data is the same as that of the graph on the right.


During insertion, the new elements are compared from the parent node of the new heap, that is, starting from the node where 2 is located. If the value is smaller than the value of the parent node, the new elements are directly inserted as the child node, if the value is greater than, the parent node is now moved down, and then compared with the parent node of the parent node until the root node, so the Insert Process, it is a path from the leaf node to the root.

Delete the maximum heap. When the maximum heap is deleted, the element is removed from the root. After deletion, the heap needs to be re-constructed so that it is still a full binary tree. For example:


First, extract the value 20 of the root node and remove the last node, that is, the node that saves 2, to make the structure still a binary tree. Then, save the value of 2, then, compare the two children at the root node to see the two children at the left and right. Who is the largest of the three elements, then who is the value of the root node, then compare the left and right children (if any) of Node 2 with the left and right children (if any) to confirm the value of the root node of the subtree.

Use an array to initialize the heap. The array elements are displayed in the following order and placed in nodes one by one.


Then, starting from the last parent node, it is the fifth node, where 10 is located, where the largest heap with this node as the root is constructed. After the structure is completed, move to the next node, the 15 node, and so on until the root node.

The following code is used:

File "maxheap. h"


# Include <iostream>
Using namespace std;
 
Template <class T>
Class MaxHeap
{
Private:
T * heap;
Int CurSize;
Int MaxSize;
Public:
MaxHeap (int maxsize = 10)
{
MaxSize = maxsize;
CurSize = 0;
Heap = new T [MaxSize + 1];
}
 
~ MaxHeap ()
{
Delete [] heap;
}
 
Int Get_Size () const
{
Return CurSize;
}
 
T Get_Max ()
{
If (CurSize = 0)
{
Cout <"heap is empty" <endl;
Return-9999;
}
Else
{
Return heap [1];
}
}
 
MaxHeap <T> & Insert (const T & x)
{
If (CurSize = MaxSize)
{
Cout <"full," <x <"insertion failed" <endl;
Return * this;
}
// Find the Insert Location for x
// I starts from the new leaf node and goes up the tree
Int I = ++ CurSize;
While (I! = 1 & x> heap [I/2])
{
Heap [I] = heap [I/2]; // move the element down
I/= 2; // move to the parent node
}

Heap [I] = x;
Cout <x <"inserted successfully" <endl;
Return * this;
}
 
MaxHeap <T> & DeleteMax (T & x)
{
// Add the largest element to x and delete it from the heap.
If (CurSize = 0)
{
X =-9999;
Return * this;
}

X = heap [1];
 
// Rebuild the heap
Heap [0] = heap [CurSize --]; // store the last element value at location 0, and then delete the location
 
// Start from the root and find a proper location for heap [0]
Int I = 1;
Int ci = 2;
 
While (ci <= CurSize)
{
// Ci is the location of a large child
If (ci <CurSize & heap [ci] Ci ++;
 
// Determine whether heap [I] can be placed.
If (heap [0]> heap [ci])
Break;

// No
Heap [I] = heap [ci];
I = ci; // move down a layer
Ci * = 2;
}
 
Heap [I] = heap [0];
Return * this;
}
 
Void Init_heap (T a [], int size, int maxsize)
{
Delete [] heap;
Heap = new T [maxsize + 1];
CurSize = size;
MaxSize = maxsize;
 
For (int j = 1; j <size + 1; j ++)
Heap [j] = a [j];
 
// Generate a maximum heap
For (int I = CurSize/2; I> = 1; I --)
{
T y = heap [I]; // the root of the subtree
 
// Locate y
Int c = 2 * I;
While (c <= CurSize)
{
If (c <CurSize & heap [c] C ++;
 
If (y> = heap [c])
Break;
 
Heap [c/2] = heap [c];
C * = 2;
}
Heap [c/2] = y;
}
}
};
Test File "main. cpp"


# Include "maxheap. h"
 
# Include <iostream>
Using namespace std;
 
Int main ()
{
MaxHeap <int> hp;
Int a [11] = {-111,5 };

Cout <"use array a to initialize the heap:" <endl;
For (int I = 1; I <11; I ++)
Cout <a [I] <"";
Cout <endl;
 
Hp. Init_heap (a, 10, 15 );
 
Int max;
Cout <"the current maximum value in the heap is:"  
Hp. DeleteMax (max );
Cout <"the biggest element in the deleted heap is:" <max <endl;
After cout <"is deleted, the largest element in the heap is:"  
Cout <"Current heap size:"  
Cout <"inserting new elements into the heap" <endl;
 
Hp. Insert (22 );
Hp. Insert (45 );
Hp. Insert (1, 214 );
Hp. Insert (16 );
Hp. Insert (21 );
Hp. Insert (1, 121 );
Hp. Insert (1, 111 );
 
Cout <"the current heap size after being inserted is:"  
Cout <"elements in the output heap from large to small" <endl;
 
Do
{
Hp. DeleteMax (max );
If (max ==- 9999)
Break;
Cout <max <"";
} While (1 );
 
Cout <endl;
 
Return 0;
}
Test results:


This structure is very efficient and the space utilization is very high when you only need to use a priority queue. However, it is not applicable to all priority queues, especially when two or more queues with different lengths need to be merged.

From: Kay's space Good Study, Day Up ~

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.