Analysis of heap ordering in STL algorithm

Source: Internet
Author: User

Heap Structure Brief


people who know the data structure should be familiar with the heap structure, the bottom of the heap is the use of arrays to achieve, but maintain the characteristics of the two-fork tree. The heap is divided into two types, the largest heap and the smallest heap, with the largest heap as an example, and the maximum heap maintains a root node greater than two around two children, while all subtrees are once again and again. Since the bottom of the heap is an array structure, here we start with the node, then go to the last node sequentially, and the node subscript decibel is 0~n-1. Structures such as:

650) this.width=650; "src=" Http://s1.51cto.com/wyfs02/M00/8B/05/wKiom1hBX3-AjFBGAABcjjuvTHY285.png "title=" 1.png " alt= "Wkiom1hbx3-ajfbgaabcjjuvthy285.png"/>

, purple means that the element in the array subscript, you can see that the value of each node is always greater than its left and right children, here does not specify the size of the child relationship, there is no rule is not the same tree node between the size of the relationship. This is the maximum heap. At the same time, it can be noted that if a large heap, the root node must be the largest nodes in the tree, similarly, if it is a small heap, the root node must be the smallest node in the tree.

Heap structure in the field of sequencing, occupy a certain low, but the STL does not directly give the heap structure, but the heap of related algorithms, written in the algorithm inside. I'm not going to do a lot of simulations here, and today I'm going to talk about how the heap algorithms given in STL are used.


The heap algorithm in algorithm

In STL, a few algorithms are given about the heap.

★make_heap

★push_heap

★pop_heap

★sort_heap

Here, we first give an example of using a heap algorithm in STL


#include  <algorithm> #include  <vector>void test () {    int  Arr[] = {1,2,3,4,5,6,7};    vector<int> vec (arr, arr+7);          //  left open right closed type     make_heap (Vec.begin (),  vec.end ());   //  by default a large heap of     pop_heap (V1.begin (),  v1.end ());           v1.pop_back ();                             sort_heap (Vec.begin (),  vec.end ());   //  heap Sort      For (Size_t i = 0; i < vec.size ();  i++)          cout<<vec[i]<< " ";     cout<<endl;}

The above code, first constructs a vector with an array, then constructs the heap for the Vector vec, pops out adjusts the first element in the vector, adjusts, then carries on the heap sorts, Finally, the results are printed out and the results are as follows:

650) this.width=650; "src=" Http://s5.51cto.com/wyfs02/M02/8B/01/wKioL1hBZBfhxxc4AAASiXstCFs740.png "title=" 2.png " alt= "Wkiol1hbzbfhxxc4aaasixstcfs740.png"/>

After reading the basic use of the heap algorithm, let's now look at how the STL provides these algorithm interfaces.

1, Make_heap

default (1) template <class randomaccessiterator>   void make_heap  (randomaccessiterator first, randomaccessiterator last);
custom (2) template <class randomaccessiterator, class  Compare>  void make_heap  (randomaccessiterator first,  randomaccessiterator last,                   Compare comp );

As mentioned earlier, the heap is divided into large piles and small heaps, and we need to determine when we build the heap, but just in the example, we do not specify the size heap. The STL specifies that the default large heap structure is not specified . As you can see from the two sets of interfaces above about Make_heap , the first is the default, there is no interface for the specified size heap, and the second is implemented here. We can use the structure of the functor to implement the parameters here.

For the example we have just given, we can now explain another question, why do we need to build vectors first? Because the underlying implementation of the heap is in the form of arrays, and vectors are high-level packages of heap arrays, the implementation of good containers in these libraries gives a lot of useful interfaces and iterators, which can really be a lot easier to use. make_heap gives the interface, the first two are any type of iterator (of course, you can also directly pass the array of pointers), whether it is make_heap or the other three functions, where the iterator interval is always left closed to the right , This is a place to be aware of.

Next, let's introduce the implementation of the pseudo function here. Or the above example, how to make the top scissors a minimum heap?

Pseudo function Structure:

struct Compare
{
BOOL operator () (int num1, int num2)
{
return NUM1 > num2;
}
};

When the heap is built, the parameter is passed to

Make_heap (Vec.begin (), Vec.end (), Compare ()); Build a small heap

Note that what I wrote above is num1 > num2, so that the vertices are built up in small piles . About Make_heap is here.


2, Push_heap and pop_heap

Push represents an element inserted into the vector , but here it is not directly inserted into the element, and it is accurate to say that its function is only to make adjustments, before Push_heap , the first need to call Vec.push_back (x) , insert an element into the tail of the vector , and then adjust it by calling the push_heap function so that the entire tree re-satisfies the heap structure.

pop_heap is similar to push_heap , and does not directly alter the number of elements in the vector . For the heap, the pop is to throw the first element of the vector , in order not to directly destroy the structure of the tree, here first call the pop_heap function, the maximum or minimum value in the heap to the tail of the vector , At the same time, the heap structure is still set up, and then the vec.pop+back () function is called and the last element is removed from the vector.

This is the whole process of inserting and deleting.

3, Sort_heap

As the name implies, Sort_heap is the meaning of the heap ordering, the heap structure is ordered, the result is that the elements in the vector become orderly. Here, build a large heap, sort the results in ascending order, build a small heap, and get the sort results descending .


Above is the basic algorithm for heap sequencing, about the new introduction of the C++11 two functions, this is not discussed here.

Here are a few things to keep in mind about the heap structure in STL:

1, because of the heap structure, is built on the vector structure, so if you want to do heap sequencing, the whole process of at least one heap (make_heap) process.

2. When the heap is completed, if you insert the element into the vector again, you need to call Push_heap (V1.begin (), V1.end ()) to make an upward adjustment; If you pop an element from the vector, you need to call Pop_ The Heap (V1.begin (), V1.end ()) makes a downward adjustment.

If there is no adjustment, an assertion error due to the heap's illegal appearance occurs during the call of the Sort_heap (V1.begin (), V1.end ()) function.

3, can not let the vector multiple tail plug, and then several times upward adjustment, will cause heap confusion, sorting will also appear when the assertion error. Of course, after multiple insertions or deletions, you can re-build the heap again, but the cost of the time will be relatively large .

Practical application of heap structure

Next, look at an interview question:

CVTE: Statistics The company employees favorite food of the first k kind of fruit

I have the above basis, I give the demo directly here

#include  <algorithm> #include  <map> #include  <string> #include  <vector >struct min{            bool operator () (PAIR&LT;STRING,&NBSP;INT&GT;&NBSP;P1,&NBSP;PAIR&LT;STRING,&NBSP;INT&GT;&NBSP;P2)              {                         return p1.second  > p2.second;            }};void  heapsort () {            vector<string>  v1 = {  "Apple",  "banana",  "apple"                          ,  "Apple",  " Apple ", " banana "                         ,  "Apple",  "Kiwi",  "Strawberry"  };             map<string, int> fruit;                         // Use map Count             for  (size_t i =  0; i < v1.size ();  i++)              {                         fruit[v1[i]]++;             }            / /  to sort    &n with a heapbsp;        vector<pair<string, int>> vec;             map<string, int>::iterator  It = fruit.begin ();             //while   (It != fruit.end ())             //{             //          vec.push_back (pair<string, int> (it->first, it->second));             //          it++;            //}             vec.insert (Vec.begin (),  fruit.begin (),  fruit.end ());   &nbSp;         make_heap (Vec.begin (),  vec.end (),  Min ());             sort_heap (Vec.begin (),  vec.end (),  min ());            int k = 3;             for  (size_t i = 0;   (i < k)  &&  (I < vec.size ());  i++)              {                         cout <<  vec[i].first << "--" <<vec[i].second<< endl;             }}int main () {             hEapsort ();             system ("Pause");             return 0;}


Heap sorting is a very important piece of data structure, and if it is in actual development, it is more recommended to be familiar with the algorithm given in STL, as mentioned above. If it is for beginners, it is recommended to have a deeper understanding of the heap structure and the underlying implementation of the algorithm, for the heap adjustment algorithm, is undeniable, is a more important part of the data structure. The next time the heap structure is simulated, a more in-depth understanding of the underlying structure is implemented.



This article from the "Twilight Back" blog, reproduced please contact the author!

Analysis of heap ordering in STL algorithm

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.