STL Source Notes (14)-Heap and Priority queue (i)

Source: Internet
Author: User

STL Source Notes (14)-Heap and priority queue

Priority_queue is a queue with a weight concept, similar to a queue, it can only push at one end, pop, the other is, each push element after the container inner elements will be arranged in a certain order, so that pop gets the element is always the maximum value of the current weight.

Obviously, to meet this condition requires some mechanism, by default, using the Max-heap large top heap to achieve, the implementation of associative heap sequencing, the use of large-top complete sequence from small to large sorting, the process is probably:

    1. Swap the root element of the heap (the maximum value in the heap) to the last
    2. The length of the heap minus 1.

This makes it possible to complete the sorting of the maximum values in the heap, just like the priority queue requires, so that the priority queue can be completed with this feature.

For a priority queue, he uses vector<T> it as its underlying default container, similar to Stack,queue, and Priority_queue is also a adapter (adapter), which is categorized ascontainer adapter

Note: in the SGI STL source code Priority_queue Source is located in the file stl_queue.h, the heap algorithm source code is located in Stl_heap.h.

Heap algorithm

The heap algorithm is the core of the implementation of the priority queue. Mainly include:

1.push_heap ()
2.pop_heap ()
3.__adjust_heap ()
4.sort_heap ()
5.make_heap ()

In addition to __adjust_heap (), the remaining four are functions that can be used externally, and if you want to implement heap ordering, you can use the above 4, 5 functions directly.

Push_heap function

The book gives a very vivid expression called percolate up operation, which assumes:
In the container vector, the first n elements (index 0~n-1) are the max-heap that are already lined up, and now the index of the element to be inserted is n, where the program will dig a hole here, call it holeindex , it can be understood that I'm inserting an element now, but I don't know where to plug it, So I dug a hole first, and then after a series of algorithms, this holeindex , to start slowly climb up to meet the big top heap conditions, actually here the climb did two things:

    1. Pull down the parent node that is smaller than value
    2. Pull the original holeindex up, occupying the original parent's position

Continuous operation until Holeindex climbs to the top (root node), and satisfies the condition of the big Top heap, at this time Holeindex has traced to the correct position, only need to fill in the value values.

Template<class_randomaccessiterator,class_distance,class_TP,class_compare>void__push_heap (_randomaccessiterator __first, _distance __holeindex, _distance __topindex, _Tp __value, _Compare _ _comp) {_distance __parent = (__holeindex-1) /2;//Parent node location   while(__holeindex > __topindex && __comp (* (__first + __parent), __value)) {//__comp default is less than: parent node is less than child node  //Adjust the position of the hole, if meet the conditions hole will always upstream* (__first + __holeindex) = * (__first + __parent);    __holeindex = __parent; __parent = (__holeindex-1) /2; } * (__first + __holeindex) = __value;//Put value in a new location}Template<class_randomaccessiterator,class_compare,class_distance,class_tp>inline void__push_heap_aux (_randomaccessiterator __first, _randomaccessiterator __last, _compare __comp, _distance*, _tp*) {//Call __push_heap directly__push_heap (__first, _distance (__last-__first)-1), _distance (0), _TP (* (__last-1)), __comp);}Template<class_randomaccessiterator,class_compare>inline voidPush_heap (_randomaccessiterator __first, _randomaccessiterator __last, _compare __comp) {__STL_REQUIRES (_RandomA  Ccessiterator, _mutable_randomaccessiterator); __push_heap_aux (__first, __last, __comp, __distance_type (__first), __value_type (__first));}
Pop_heap and __ADJUST_HEAP functions

and push_heap corresponding to the "out of the heap" operation, in the heap sorting, we have built the heap "out of the heap", the operation is each time the top root element of the heap to the end of the container, the length of the heap minus 1, and then heap heap operation, repeated until all the elements in the heap out, Because the heap operation is out of the heap top element each time, that is, the maximum value, so after the completion of the heap operation to complete the sorting work.

Pop_heap and Push_heap correspond to the percolate down operation, it is easy to understand that the root element of the heap is taken away, where the original root element is an empty node without elements, that is, the so-called Holeindex, This is to adjust the holeindex to the right place, holeindex before the element is a heap, actually do the work is:

    1. Find the holeindex corresponding to the larger of the two children to change it to holeindex position
    2. Place Holeindex below the index of the larger child
    3. Repeat the above, and the final Holeindex will fall at a leaf node.

The 2nd above needs to consider cases where there is no right subtree, for example:


When you go back to the original 65 node (at index 2), there is no right node at this time, right node index Second==len

Since the value is not considered at this time from the end of the container, the index of the heap is 0~holeindex (simulating the process can be easily obtained at this time holeindex at the leaf node) of the element to perform a push_heap operation, Causes value to be inserted in the appropriate position.

So, Pop_heap's work is actually very simple, and the main task is to re-adjust the remaining elements to a heap after maximum value out of the heap.

//4.Template<class_randomaccessiterator,class_distance,class_tp>void__adjust_heap (_randomaccessiterator __first, _distance __holeindex, _distance __len, _Tp __value) {_Distance __topindex = __holeindex;//holeindex at the top_distance __secondchild =2* __holeindex +2;//Start with the right child   while(__secondchild < __len) {//Indicates that the Holeindex has not yet reached the leaf node, or stopped  //Take the maximum value of the left and right child    if(* (__first + __secondchild) < * (__first + (__secondchild-1))) __secondchild--; * (__first + __holeindex) = * (__first + __secondchild);//Older children are raised__holeindex = __secondchild;the//holeindex is traced__secondchild =2* (__secondchild +1); }if(__secondchild = = __len) {//Current holeindex only left child* (__first + __holeindex) = * (__first + (__secondchild-1)); __holeindex = __secondchild-1; } __push_heap (__first, __holeindex, __topindex, __value);//re-insert}//3.Template<class_randomaccessiterator,class_TP,class_distance>inline void__pop_heap (_randomaccessiterator __first, _randomaccessiterator __last, _randomaccessiterator __result, _Tp __va Lue, _distance*) {*__result = *__first;//First assign the maximum value in the heap to the end of the heap  //The last here has been completed minus 1 operations  //Heap Operation__adjust_heap (__first, _distance (0), _distance (__last-__first), __value);}//2.Template<class_randomaccessiterator,class_tp>inline void__pop_heap_aux (_randomaccessiterator __first, _randomaccessiterator __last, _tp*) {///Direct call, where the value of the last element in the heap has been fetched, and the iterator variable of the last element in the heap__pop_heap (__first, __last-1, __last-1, _TP (* (__last-1)), __distance_type (__first));}//1.Template<class_randomaccessiterator>inline voidPop_heap (_randomaccessiterator __first, _randomaccessiterator __last) {__stl_requires (_RandomAccessI  Terator, _mutable_randomaccessiterator); __stl_requires (TypeNameIterator_traits<_randomaccessiterator>::value_type, _lessthancomparable); __pop_heap_aux (__first, __last, __value_type (__first));//Direct call}
Make_heap and Heap_sort

These two functions implement the heap ordering.
Make_heap is to convert a piece of existing data into a heap, the operation is, from the first non-leaf node forward to the heap operation, why choose the last non-leaf node? Because, the heap operation is to Holeindex, and now you are the leaf node, how to lower?
As for the last non-leaf node calculation formula:
INd ex=(LeN?2)/2 (1)
Where Len is the length of the array.

The Heap_sort function is simple, and the pop_heap operation can be performed continuously:

Template<class_randomaccessiterator,class_TP,class_distance>void__make_heap (_randomaccessiterator __first, _randomaccessiterator __last, _tp*, _distance*) {if(__last-__first <2)return; _distance __len = __last-__first;//Find the first subtree to be re-queued (because perlocate down is required, and the leaf node does not need to do that)_distance __parent = (__len-2)/2; while(true) {__adjust_heap (__first, __parent, __len, _TP (* (__first + __parent)));if(__parent = =0)return;  __parent--; }}//Convert a piece of existing data into a heap ... In the heap sort, it's build_heap.Template<class_randomaccessiterator>inline voidMake_heap (_randomaccessiterator __first, _randomaccessiterator __last) {__stl_requires (_RandomAccessIterator, _  Mutable_randomaccessiterator); __stl_requires (TypeNameIterator_traits<_randomaccessiterator>::value_type, _lessthancomparable); __make_heap (__first, __last, __value_type (__first), __distance_type (__first));}
//每次将一个极大值放到尾端template <class _RandomAccessIterator>void sort_heap(_RandomAccessIterator __first, _RandomAccessIterator __last){  __STL_REQUIRES(_RandomAccessIterator, _Mutable_RandomAccessIterator);  __STL_REQUIRES(typename iterator_traits<_RandomAccessIterator>::value_type,                 _LessThanComparable);  while1)    pop_heap(__first, __last--);}

STL Source Notes (14)-Heap and Priority queue (i)

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.