The 4 functions associated with the heap in the STL--Build heap Make_heap (), add Data push_heap () to the heap, delete data pop_heap () and heap sort sort_heap () in the heap:
Header file #include <algorithm>
The following _first and _last are iterators (pointers) that can be accessed randomly, _comp is a comparison function (functor), and its rule--returns false if the first argument of the function is less than the second argument should return true.
Build heap
Make_heap (_first, _last, _comp)
The default is to build the maximum heap. For an int type, the smallest heap can be obtained by passing in the third argument to Greater<int> ().
The CMP function format is as follows:
BOOL cmp(int a,int b)
{
Return a>b;
}
Or as my other blog post: http://blog.csdn.net/kaisa158/article/details/46853939
Adding data to the heap
Push_heap (_first, _last)
To first add data to the container, then call Push_heap ()
Delete data in the heap
Pop_heap (_first, _last)
To First call Pop_heap () and then delete the data in the container
Heap Sort
Sort_heap (_first, _last)
After sorting, it's no longer a valid heap.
detailed description of the heap:
The heap is divided into large top piles and small top piles. What is introduced and implemented here is the large top heap.
Introduction to the main related algorithms of the heap
PUSH_HEAP algorithm This operation is to add a node to the heap. In order to satisfy the conditions of the complete binary tree, the newly added element must be placed at the bottom layer as the leaf node and fill the first space from left to right, where it is placed at the end () of the underlying container vector.
Obviously, the addition of new elements is likely to make the heap not satisfy the nature of the large top heap---each node's key value is greater than or equal to the key value of its child nodes. In order to adjust the characteristics of the large top heap, we perform an upstream (percolate up) operation: Compare the new node to the parent node and, if its key value is larger than the parent node, swap the parent-child position so that it goes upstream until it does not need to be exchanged or reached the root node.
The pop_heap algorithm takes the root node out of this operation. For the large top heap, the node with the largest value in the heap is obtained, and for the small top heap, the node with the lowest value in the heap is obtained. Instead of deleting the node directly, the STL implementation places it at the end of the underlying container vector. The node at the original end is inserted into the previous appropriate position.
We first save the node value at the end of the original vector, and then store the root node value here. In order to insert the value of the original end node into the appropriate location and rebuild the large top heap, we implement the following adjustment heap:
Perform a percolate down operation starting from the root node, exchanging the empty node (initially the root node) and the larger child node, and continuing down until the leaf node is reached. Then the saved original container vector end node is assigned to the hole node that has reached the leaf layer.
Note that this is not the end. Because it may not yet meet the characteristics of the big top heap. You also need to perform an upstream operation. In this way, the large top heap is rebuilt.
MAKE_HEAP algorithm This operation builds the heap based on the existing elements.
Each element is stored in the underlying container vector.
Building a heap is a process of constantly adjusting the heap (the operation of the tuning heap in the previous POP_HEAP algorithm)---by constantly adjusting the subtree so that the subtree satisfies the properties of the heap so that the whole tree satisfies the nature of the heap.
The leaf node obviously needs to be adjusted, and the first sub-tree that needs to perform the adjustment operation is the first non-leaf node from the backward forward. The heap can be built by performing an adjustment operation on each subtree from this node forward to the root node.
Sort_heap algorithm heap sorting algorithm. After you do this, the elements in the container vector are arranged in small to large order.
After constructing the large top heap, the POP_HEAP algorithm is continuously executed to remove the elements from the top of the heap. Because each time the largest element is obtained, it is placed at the very end of the container vector. So the elements in the last vector are arranged from small to large.
#include <cstdio> #include <vector> #include <algorithm> #include <functional>using namespace Std;void printfvectorint (vector<int> &vet) {for (Vector<int>::iterator pos = Vet.begin (); pos! = Vet.end (); pos++) printf ("%d", *pos);p Utchar (' \ n ');} int main () {const int MAXN = 20;int A[maxn];int i;for (i = 0; i < MAXN; ++i) A[i] = rand ()% (MAXN * 2);//dynamic application vector and ve ctor Build heap vector<int> *pvet = new Vector<int> (;p vet->assign (A, A + MAXN);//will interval [first,last] Element is assigned to the current vector container,//or the element with n values x is in the vector container, which clears the previous contents of the vector container. Build Heap Make_heap (Pvet->begin (), Pvet->end ()); Printfvectorint (*pvet);//Add new data to the container first, then call Push_heap () Pvet->push_back;p ush_heap (Pvet->begin (), pvet- >end ()); Printfvectorint (*pvet);//delete data to call Pop_heap () First, then delete pop_heap (Pvet->begin (), Pvet->end ()) in the container;p vet->pop_back ();p Op_heap (Pvet->begin (), Pvet->end ());p vet->pop_back (); Printfvectorint (*pvet);//Heap Sort Sort_heap (Pvet->begin (), Pvet->end ()); PrintfVectorint (*pvet);d elete Pvet;return 0;}
after mastering its basic usage, we use this heap to sort and"Vernacular classic Algorithm series"in theHeap Sort,Quick Sort,Merge SortFor a personality test.
#include <cstdio> #include <algorithm> #include <ctime>using namespace std;//---------------------- --Quick Sort----------------------------void quick_sort (int s[], int l, int r) {if (L < r) {int i = l, j = r, x = S[l];while (i < J) {while (I < J && S[j] >= x)//right-to-left find the first number less than x j--; if (i < j) s[i++] = S[j];while (i < J && S[i] < x)//From left to right find the first number greater than or equal to x i++; if (i < j) s[j--] = s[i];} S[i] = X;quick_sort (S, l, i-1); Recursive call Quick_sort (s, i + 1, r);}} ------------------------Merge Sort----------------------------//There will be two ordered series A[first...mid] and A[mid ... Last] Merge. void Mergearray (int a[], int first, int mid, int last, int temp[]) {int i = First, J = mid + 1;int m = Mid, n = last;int K = 0;while (i <= m && J <= N) {if (A[i] < a[j]) temp[k++] = a[i++];elsetemp[k++] = a[j++];} while (i <= m) temp[k++] = A[i++];while (j <= N) temp[k++] = a[j++];for (i = 0; i < K; i++) A[first + i] = temp[i];} void mergesort (int a[], int first, int last, int temp[]){if (first < last) {int mid = (first + last)/2;mergesort (A, first, mid, temp); Left ordered MergeSort (A, mid + 1, last, temp); Right ordered Mergearray (a, first, mid, last, temp); Merge two ordered columns}}bool mergesort (int a[], int n) {int *p = new Int[n];if (p = = NULL) return False;mergesort (A, 0, n-1, p); Retu RN true;} ------------------------heap sort---------------------------inline void Swap (int &a, int &b) {int c = A;a = B;b = C;} Build minimum heap//start with the I-node adjustment, n for the total number of nodes starting from 0 to calculate the child node of the I node is 2*i+1, 2*i+2void minheapfixdown (int a[], int i, int n) {int J, temp;temp = A[i]; j = 2 * i + 1;while (J < N) {if (j + 1 < n && a[j + 1] < A[J])//Find the smallest j++;if (a[j] >= temp) in the left and right child break;a [i] = a[j]; Move the smaller sub-node upward, replacing its parent node i = j;j = 2 * i + 1;} A[i] = temp;} Establish minimum heap void makeminheap (int a[], int n) {for (int i = N/2-1; I >= 0; i--) Minheapfixdown (A, I, n);} void Minheapsorttodescendarray (int a[], int n) {for (int i = n-1; I >= 1; i--) {Swap (A[i], a[0]); Minheapfixdown (A, 0, i);}} const int MAXN = 5000000;int a[mAxn];int B[MAXN], C[MAXN], D[maxn];int main () {int I;srand (time (NULL)), for (i = 0; i < MAXN; ++i) A[i] = rand () * RAND (); Note Rand () produces a number between 0 and 0x7fff for (i = 0; i < MAXN; ++i) d[i] = c[i] = B[i] = A[i]; clock_t Ibegin, iend;printf ("--current data volume is%d--by morewindows (http://blog.csdn.net/MoreWindows)--\n", MAXN);//Quick Sort printf ("Quick sort:"); ibegin = Clock (); Quick_sort (A, 0, MAXN-1), iend = Clock ();p rintf ("%d milliseconds \ n", iend-ibegin);//merge sort printf ("merge sort: "); ibegin = Clock (); MergeSort (b, maxn); iend = Clock ();p rintf ("%d milliseconds \ n", iend-ibegin);//Heap sort printf ("heap sort:"); ibegin = Clock (); Makeminheap (c, MAXN); Minheapsorttodescendarray (c, MAXN), iend = Clock ();p rintf ("%d milliseconds \ n", Iend-ibegin),//stl heap sort printf ("Heap Ordering in STL:"); Ibegin = Clock (), Make_heap (d, D + maxn), Sort_heap (d, D + maxn), iend = Clock ();p rintf ("%d milliseconds \ n", Iend-ibegin); return 0;}
test results for 100000 (100,000) data:
Test results for 500000 (500,000) data:
Test results for 1000000 (1 million) data:
Test results for 5000000 (5 million) data:
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
The heap of STL