Algorithm Introduction Learning heap + heap ordering + Heap composition Priority queue

Source: Internet
Author: User

Note: The heap is divided into the largest heap and the smallest heap, and the heap we are discussing below refers to the largest heap, and the minimum heap is similar in nature.

A heap data structure is an array object that can be treated as a complete binary tree (this binary tree is filled with each layer except the last one); we use an array to store a heap that represents the array of heaps with two properties: Length[a] Represents the number of elements in an array, Headsize[a] Represents the number of elements in the heap (that is, the elements in the array are not necessarily elements in the heap).
Some of the properties of the heap are given without proof below:
For any one node, its parent node is I/2 (i>1); left son: 2*i, right son: 2*i+1;
For maximum heap per node: a[parent[i]]>=a[i]
The height of the heap containing n elements is LGN
The number of leaf nodes containing n-element heaps is: n/2+1,n/2+2,......, N.

I. Heap adjustment functions-preserving the nature of the heap
Consider such a situation, if for node I, its left and right subtree is a valid large root heap, but node I does not satisfy the nature of the heap, then we can adjust so that I is the root node of the tree to meet the nature of the heap. So what is the specific adjustment process? We make largest represent the largest of the a[i],a[i*2],a[2*i+1], if largest is not I then we exchange A[i] and a[largest] and recursively go into the subtree with largest as the root node to continue the adjustment. The specific code is implemented as follows:

voidMaxheadfly (int*a,intIintHeadsize) {/   //Heap adjustment function: Adjust the subtree with the root of I so that it conforms to the characteristics of Dagen (in the case where the left and right subtree are legal Dagen)  ///The   maximum heap adjustment function is the most important function in heap sorting, and it is an important part of the following functions;   ///The main idea is to adjust the root node and then recursively adjust the affected left (right) subtree until the leaf node        intL=2*i,r=2*i+1;///Remove the number of the left and right   son node of node I        intlargest;///   Record the maximum node number        if(a[i]<a[l]&&l<=headsize) largest=l;Elselargest=i;if(a[largest]<a[r]&&r<=headsize) Largest=r;if(largest!=i) {///   recursively adjust the affected subtreeSWP (A[i],a[largest]);        Maxheadfly (a,largest,headsize); }}

Two. Build the heap
The building of a heap is actually a process of constantly invoking the adjustment function. We know that the leaf nodes of a heap can be regarded as a large heap with only one element being valid, so that if we start by invoking the adjustment function from the first non-leaf node, we can guarantee that the left and right subtree of the node being adjusted is a valid large heap, which can ensure that the tree being adjusted is also a large root heap. The specific code is implemented as follows:

voidBuildmaxhead (int*a,intN) {  ///Max Heap Establishment function: make the array into a large heap by adjusting the elements in an orderly manner.    ///By the nature of the complete binary tree: A heap containing n elements whose leaf node number is n/2+1,n/2+2 ... n;  ///   for a leaf node can be regarded as a legal single element of the large root heap, by the nature of the Maxheadfly function can be known  ///   If node I does not satisfy the nature of Dagen, but its left and right subtree are legal large root heap, then call Maxheadfly  ////   adjust to I as root node can constitute a valid large heap, and a node of the left and right son node number is greater than its  ///   So we can call the heap's adjustment function sequentially from the numbered N/2--1 node, then we can get a big heap.    for(inti=n/2; i>=1; i--) Maxheadfly (a,i,n);}

Three. Heap sequencing
As the name suggests, heap ordering is to use the nature of the heap to sort the array, for a heap we can use the nature of its root node is the largest element, this time we can be a[1] and a[headsize] Exchange, after the exchange of Headsize value minus 1, and call Maxheadfly (a,1,headsize) to adjust the heap so that a[1] becomes the largest of the remaining elements, and then continue the process. Finally, an ordered array is obtained. The time complexity of heap sequencing is NLGN; The specific code is implemented as follows:

voidHeadsort (int*a,intN) {  ///heap sort function: Realize the order of n elements in the array from small to large, time complexity nlgn  ////   We know that if an array consists of a large heap, then its root node a[1] must be the largest element    ///At this time if we will a[1] and A[n] interchange, then A[n] is the largest element;    ///But a[1--n-1] the heap may no longer satisfy the nature of the maximum heap, and we then call Maxheadfly (a,1,n-1) to adjust to the maximum heap  /   ///And then A[1] is the largest element in a[1--n-1], then we exchange a[1] and a[n-1], then a[n-1] and A[n] are ordered.   ///   Continue this process until the heap size is reduced to 2, and then the last adjustment exchange, the A array is small to large arrangement.   /   //Time complexity: Establish a large root heap time O (n), adjust the time O (LGN) for a total of n-1 times, so the total complexity nlgnBuildmaxhead (A,n);///   build a big root heap        intHeadsize = n; for(inti=n;i>=2; i--)///   The scale of the heap continues to decrease{SWP (a[1],a[i]); headsize--;///   Reduce the size of the heap after ExchangeMaxheadfly (A,1, headsize);///   root node changed, re-adjusted to large root heap}}

The following is a complete list of heap-sorted codes:

#include <iostream>#include <cstdio>#include <cstring>using namespace STD;intSwpint&a,int&AMP;B) {intT=a;        A=b; b=t;}voidMaxheadfly (int*a,intIintHeadsize) {intL=2*i,r=2*i+1;///Remove the number of the left and right son node of node I        intlargest;/// record the maximum node number        if(a[i]<a[l]&&l<=headsize) largest=l;Elselargest=i;if(a[largest]<a[r]&&r<=headsize) Largest=r;if(largest!=i) {/// recursively adjust the affected subtreeSWP (A[i],a[largest]);        Maxheadfly (a,largest,headsize); }}voidBuildmaxhead (int*a,intN) { for(inti=n/2; i>=1; i--) Maxheadfly (a,i,n);}voidHeadsort (int*a,intN) {buildmaxhead (a,n);/// build a big root heap        intHeadsize = n; for(inti=n;i>=2; i--)/// The scale of the heap continues to decrease{SWP (a[1],a[i]); headsize--;/// reduce the size of the heap after ExchangeMaxheadfly (A,1, headsize);/// root node changed, re-adjusted to large root heap}}intMain () {intn=5, a[Ten];cout<<"Please enter"<<n<<"Number:"<<endl; for(intI=1; i<=n;i++)Cin>>a[i]; Headsort (A,n);cout<<"sorted array after:"<<endl; for(intI=1; i<=n;i++)cout<<a[i]<<" ";cout<<endl;return 0;}

Four. Priority queue
For the general queue, satisfy the first-in-one-out nature (team tail, to the first team), but for the priority queue, each time is the largest/smallest element out of the team. The heap can implement the basic operation of the priority queue, and the nature of the heap is also utilized. Priority queue some specific function operations and their principles are shown in the code below.

#include <iostream>#include <cstring>#include <cstdio>usingnamespace Std;#define INF 0x3f3f3f3f///   General queue satisfies the nature of FIFO, while the preferred queue is different, its  ///always the largest/smallest first-out team. With the help of the nature of the heap, we can///   for any operation of the preferred queue within the LGN timevoidSwpint&a,int&AMP;B) {intT=a;      A=b; b=t;}voidMaxheadfly (int*a,intIintHeadsize)///   heap adjustment function{intlargest;intl=i*2, r=2*i+1;if(a[i]<a[l]&&l<=headsize) largest=l;Elselargest=i;if(A[largest]<a[r]) largest=r;if(largest!=i)             {SWP (a[i],a[largest]);        Maxheadfly (a,largest,headsize); }}voidBuildmaxhead (int*a,intN///   Build a maximum heap{intk=n/2; for(inti=k;i>=1; i--) Maxheadfly (a,i,n);}///The   following are priority queue operationsintMaxnum (int*A)///   Remove the largest element{returna[1];///   Direct return}voidIncreasekey (int*a,intXintK) {///The value of the element in the   heap numbered X to k,k cannot be less than the original value.        This elevation can only cause the parent node to not satisfy the nature of the maximum heap, so the check for direct upward recursionA[x]=k; while(x>1&&a[x/2]<a[x]) {SWP (a[x],a[x/2]); x=x/2; }}intExtractmax (int*a,int&headsize) {///   Remove the largest element in the heap and return its value      ///   thought similar to one adjustment of heap ordering: We first exchange values of a[1] and A[headsize]        ////Then subtract the value of Headsize by 1 (equivalent to removing a leaf node);       ///Maxheadfly (a,1,headsize) to adjust the heap to ensure the nature of the heap. SWP (a[1],a[headsize]);      headsize--; Maxheadfly (A,1, headsize);returnA[headsize];}voidInsert (int*a,int&headsize,intx) {///   Add an element x to the heap       ///thought: First add a leaf node to the heap and assign its value to-inf     ////   and then call the above adjustment function to adjust the value of the leaf node to xheadsize++;///   Add a leaf nodea[headsize]=-1*inf; Increasekey (a,headsize,x);}intMain () {inta[Ten];intn=5; cout<<"Please enter 5 numbers:"<<endl; for(intI=1; i<=n;i++) cin>>a[i];intHeadsize=n; Buildmaxhead (A,n);///   Remove the largest element in the queuecout<<"The biggest element is:"<<maxnum (a) <<endl;        Extractmax (a,headsize); cout<<"After removing the largest element, the largest of the remaining elements is:"<<maxnum (a) <<endl;///Add the   4th element toIncreasekey (A,4, -); cout<<"When you increase the 4th element to 100, the maximum element is:"<<maxnum (a) <<endl;///   Insert 110 into the queueInsert (A,headsize, the); cout<<"After inserting 110, the maximum element is:"<<maxnum (a) <<endl;return 0;}

Algorithm Introduction Learning heap + heap ordering + Heap composition Priority queue

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.