Heap and heap sequencing of data structures and algorithms

Source: Internet
Author: User

In the data structure, the heap is actually a completely binary tree . We know that there is also a storage area called a heap in memory, but this is a completely different concept from the heap in the data structure. In the data structure, the heap is divided into Dagen and small Gan , Dagen is the key word of the root node is greater than or equal to any child node of the keyword, and its left and right sub-tree are Dagen; small Gan and Dagen are the exact opposite. In C + + STL, the priority queue Priority_queue structure is the implementation of the heap structure. Come down and do it yourself real a heap structure, including heap_init,heap_insert,heap_top operations.

1, the implementation of the heap

Because the heap is a completely binary tree, we can use sequential tables, and the heap can only be used in sequential tables. We use vectors.

  (1) Initialization of the heap

  Basic idea of the initialization of the heap: first the initial array is a disorganized sequence, but if there is only one element in the heap heap[0], then heap[0] itself is a heap and then joins Heap[1] to adjust the heap; continue to join Heap[2] ... Until the adjustment of all elements is complete.

voidSIFT_UP (vector<int> &heap,intindex) {     while((index+1)/2-1>=0){        if(Heap[(index+1)/2-1] <Heap[index]) {Swap (&heap[(index+1)/2-1],&Heap[index]); Index= (index+1)/2-1; }Else             Break; }}voidHeap_init (vector<int> &heap) {    if(Heap.empty ())return ;  for(intI=1; I) {sift_up (heap,i); }}

  (2) inserting elements into the heap

  Put the inserted element at the end of the heap, and then adjust the heap upward.

void Heap_insert (vector<int> &heap,int  element) {    Heap.push_back ( Element);    Sift_up (Heap,heap.size ()-1);}

  (3) Remove the elements from the top of the heap

  After removing an element, fill the position of the first element with the last element, and then adjust the heap downward.

voidSift_down (vector<int> &heap,intindex) {     while(index*2+2<heap.size ()) {        if(heap[index*2+1]>=heap[index*2+2] && heap[index]2+1]) {Swap (&heap[index],&heap[index*2+1]); Index= index*2+1; }Else if(heap[index*2+1]2+2] && heap[index]2+2]) {Swap (&heap[index],&heap[index*2+2]); Index= index*2+2; }Else             Break; }}BOOLHeap_top (vector<int> &heap,int*Res) {    if(Heap.empty ())return false; *res = heap[0]; heap[0] = Heap[heap.size ()-1]; Heap.erase (Heap.end ()-1); Sift_down (Heap,0); return true;}

2. Heap Sequencing

First initialize the heap, and then click to remove the value from the top of the heap. Here is the big root heap, so it is sorted from large to small.

void heap_sort (vector<int> &vec) {    heap_init (VEC);     int len = vec.size ();      while (len--) {        int  num;        Heap_top (VEC,&num);        printf ("", num);    }}

The time complexity of the heap ordering is O (nlog2n), and the steps ordered from above can be seen as an unstable sort. But it is the same as the selection sort, merge sort the time complexity does not change with the distribution of the sequence. For insertion sort and bubble sort, when the input sequence is ordered or basically ordered, their complexity is reduced to O (n), and the fast sort degrades to O (N2).

So in the concrete application, we should choose which sort method according to the input sequence, the specific problem is analyzed concretely. Because of the special sorting structure and excellent performance of the heap ordering, heap ordering can be used in many cases.

3. Application of heap Sequencing

(1) The largest number of k in a sequence of n numbers.

This is a very common sort of algorithm problem.

Method One: Directly to the number of these n order, and then take the number of K. The time complexity is at least O (nlog2n).

Method Two: Learn from the idea of fast-track, do not need to fully implement the fast row, just to achieve a part of the fast row to get the largest number of K. The complexity is O (nlog2k).

Method Three: The hash can be used to sort, first the number of K started in n into the hash table, and then sequentially from the remaining number of n-k to take out one, and the hash table in the number of K compared to the minimum number of each elimination. The time complexity is O ((n-k) *k).

Method Four: Take out the number of K starting in N, create a small Gan, and then from the remaining number of n-k, take one number at a time to insert the small root heap, and then delete the heap top element (the lowest value in the heap). The time complexity is O (* (n-k) *lg2k).

Admittedly, the use of heaps to find the largest number of K performance is the best, but the benefits are not so little!! Let's imagine that if the input sequence is large, that is, the value of n is so large that it cannot be stored in memory, then the method one and method two are used, of course, the method can achieve the goal by using the merge sort, but how many Io is needed at this time? If you choose method Four, you need at most only (n-k) secondary IO, of course, three is the same way, only need to compare k times each time.

Full code See: Https://github.com/whc2uestc/DataStructure-Algorithm/tree/master/heap

  All rights reserved, welcome reprint, reprint please indicate source.

Heap and heap sequencing of data structures and algorithms

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.