Heap: Heap is a two-fork tree with special properties
Each node is larger than its left and right son's two-prong tree called the Big Top pile
Each node is smaller than its left and right son's two-pronged tree called a small top heap.
Heap Sort Plot:
Given an array of a[]={16,7,3,20,17,8}, it is sorted by heap.
First, a complete binary tree is constructed based on the array element, which gets
Then you need to construct the initial heap, then start the adjustment from the last non-leaf node, and the adjustment process is as follows:
20 and 16 result in 16 not satisfying the nature of the heap and therefore need to be re-adjusted
This will get the initial heap.
That is, each adjustment is from the parent node, the left child node, right child node three of the largest selection of the parent node to Exchange (after the Exchange may cause the exchange of the child node does not satisfy the nature of the heap, so after each exchange to re-exchange the child node to adjust). Once you have the initial heap, you can sort it out.
At this point 3 is in the heap top of the property of the heap, you need to adjust the continued adjustment
Code:
#include <iostream> #include <cstdio> #include <cstring>using namespace Std;int q[10005];void Heapadjust (int loc,int len) {int pos=loc; Maximum position (left son right son himself) int left_child=2*loc; int right_child=2*loc+1; if (LOC<=LEN/2)//leaves no left and right son so don't compare {if (left_child<=len&&q[left_child]> Q[pos]//small top heap change less than the same as Pos=left_child; if (Right_child<=len&&q[right_child]>q[pos]) pos=right_child; if (pos!=loc)//MAX does not compare after loc position swap {swap (q[pos],q[loc]); Heapadjust (Pos,len); }} return; void heapsort (int len) {int i; for (i=len/2;i>=1;i--)//initialize becomes large top heap heapadjust (I,len); for (i=len;i>=1;i--) {swap (q[1],q[i]); The maximum value is placed at I heapadjust (1,i-1); Find the top I-1 max} return;int main () {int n,i; scanf ("%d", &n); Enter n number for (i=1; i<=n; i++) scanf ("%d", &q[i]); Heapsort (n); for (I=1; i<=n; i++) cout<<q[i]; cout<<endl; return 0;}
The sorting principle of data structure heap and its realization