Data Structure: heap

Source: Internet
Author: User

Heap is often used to implement priority queues. In such queues, the elements to be deleted are those with the highest (lowest) priority. Any priority element can be inserted into the queue at any time. It is a general term for a special data structure in computer science.

I. Definition of heap
The maximum (minimum) heap is a tree in which the key value of each node is not smaller than or greater than the key value of its child (if any. The big top heap is a Complete Binary Tree and also a hidden tree. A small top heap is a completely Complete Binary Tree and a minimum tree.

Note:


Any subtree In the heap is also a heap.
The Heap discussed above is actually Binary Heap, which can be defined similarly.
The following are examples of the maximum and minimum heaps:

 
 


Ii. Basic operations supported
The heap supports the following basic operations:
Build: Create an empty heap;
Insert: insert a new element into the heap;
Update: Upgrade new elements to conform to the heap nature;
Get: gets the value of the current heap top element;
Delete: delete the heap top element;
Heapify: Make the heap that deletes the heap top element become heap again.
Some heap implementations also support other operations. For example, the Fibonacci heap supports checking whether an element exists in a heap.

3. Heap Application
1. Heap sorting
HeapSort is a tree-based sorting method. Www.2cto.com
The characteristic of heap sorting is that during the sorting process, R [l .. n] As a Complete Binary Tree ordered storage structure, using the inherent relationship between the parent and child nodes in the Complete Binary Tree [see the binary tree ordered storage structure ], select the record with the maximum or minimum keyword in the unordered area.
In order to directly select sorting from R [1 .. n] to select the record with the smallest keyword. The record must be compared n-1 times, and then in R [2 .. n] in the selection of the minimum keyword record, and need to do a N-2 comparison. In fact, many comparisons in the next N-2 comparison may have been done in the previous n-1 comparison, but since these comparison results were not retained in the previous sort, therefore, these comparison operations are repeated during the next sorting.
Partial comparison results can be saved in a tree structure to reduce the number of comparisons.
Heap sorting utilizes the largest (or least) keyword of the top record of a large root heap (or a small root heap) so that the largest (or least) keyword is selected in the current unordered area) keyword record becomes simple.
(1) the basic idea of sorting with big roots

First, build the initial file R [1. n] into a large root heap, which is the initial unordered zone.
Then, the record R [1] (heap top) with the largest keyword is exchanged with the last record R [n] In the unordered zone to obtain the new unordered zone R [1 .. n-1] And the ordered zone R [n], and meet the requirements of R [1 .. n-1]. keys ≤ R [n]. key
Since the new root R [1] After the swap may violate the heap nature, the R [1 .. n-1] of the unordered zone should be changed to the heap. Then re-set R [1 .. in n-1], the record R [1] with the largest keyword is exchanged with the last record R [n-1] In the interval, and a new unordered zone R [1 .. n-2] and ordered zone R [n-1 .. n], and still satisfies the relationship R [1 .. n-2]. keys ≤ R [n-1 .. n]. keys, also set R [1 .. n-2] adjusted to heap. Until there is only one element in the unordered area.
(2) Basic operations on the Sorting Algorithm of the big root heap:

Initialization: Constructs R [1. n] as the initial heap;
Basic operations for sorting each trip: swap the top record R [1] of the unordered zone with the last record in the interval, then adjust the new unordered area to the heap (also weigh and build the heap ).
Note:

You only need to perform n-1 sort and select a large n-1 keyword to make the file ascending and orderly.
Sorting with a small root heap is similar to using a large root heap, but the sorting result is descending and ordered. Opposite to Direct selection: at any time, unordered areas in heap sorting are always before the ordered areas, the ordered area gradually expands from the back to the end of the original vector to the end of the whole vector.
(3) Algorithm Implementation
[Cpp]
//////////////////////////////////////// ////////////////////////////
// Heap sorting
Template <class T>
Void Sort: HeapSort (T arr [], int len ){
Int I;

// Create a sub-heap
For (I = len/2; I> = 1; I --){
CreateHeap (arr, I, len );
}

For (I = len-1; I> = 1; I --){
Buff = arr [1];
Arr [1] = arr [I + 1];
Arr [I + 1] = buff;

CreateHeap (arr, 1, I );
}
}
 
 
// Create a heap
Template <class T>
Void Sort: CreateHeap (T arr [], int root, int len ){
Int j = 2 * root; // root's left child, right (2 * root + 1)
T temp = arr [root];
Bool flags = false;

While (j <= len &&! Flags ){
If (j <len ){
If (arr [j] <arr [j + 1]) {// Left child is less then right child
+ + J; // Move the index to the right child
}
}

If (temp <arr [j]) {
Arr [j/2] = arr [j];
J * = 2;
} Else {
Flags = true;
}
}
Arr [j/2] = temp;
}

//////////////////////////////////////// ////////////////////////////
// Heap sorting
Template <class T>
Void Sort: HeapSort (T arr [], int len ){
Int I;
 
// Create a sub-heap
For (I = len/2; I> = 1; I --){
CreateHeap (arr, I, len );
}
 
For (I = len-1; I> = 1; I --){
Buff = arr [1];
Arr [1] = arr [I + 1];
Arr [I + 1] = buff;

CreateHeap (arr, 1, I );
}
}


// Create a heap
Template <class T>
Void Sort: CreateHeap (T arr [], int root, int len ){
Int j = 2 * root; // root's left child, right (2 * root + 1)
T temp = arr [root];
Bool flags = false;
 
While (j <= len &&! Flags ){
If (j <len ){
If (arr [j] <arr [j + 1]) {// Left child is less then right child
+ + J; // Move the index to the right child
}
}

If (temp <arr [j]) {
Arr [j/2] = arr [j];
J * = 2;
} Else {
Flags = true;
}
}
Arr [j/2] = temp;
} 2. Select the maximum (minimum) Number of the first k.
Idea: select the first k largest (smallest) data in a large unordered array. The most intuitive way is to sort all the data in the array in order, then, output the first k data records with the largest (minimum. However, sorting requires O (nlogn) time, and we do not need the first k largest (minimum) Elements to be ordered. In this case, we can create the minimum heap of k elements (obtain the maximum values of the first k) or the maximum heap (obtain the minimum values of the first k). We only need to traverse the array once, it takes only logk time to insert elements into the heap. This speed is optimistic. Using the heap to obtain the first k maximum (minimum) elements is particularly suitable for processing massive data.

Code:


[Cpp]
Typedef multiset <int, greater <int> intSet;
Typedef multiset <int, greater <int> >:: iterator setIterator;
 
Void GetLeastNumbers (const vector <int> & data, intSet & leastNumbers, int k)
{
LeastNumbers. clear ();
 
If (k <1 | data. size () <k)
Return;
 
Vector <int>: const_iterator iter = data. begin ();
For (; iter! = Data. end (); ++ iter)
{
If (leastNumbers. size () <k)
LeastNumbers. insert (* iter );
 
Else
{
SetIterator iterGreatest = leastNumbers. begin ();
 
If (* iter <* (leastNumbers. begin ()))
{
LeastNumbers. erase (iterGreatest );
LeastNumbers. insert (* iter );
}
}
}

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.