This thing ... Easy, eh?
But it seems like a year ago, there is no habit of blogging
Well, let's summarize.
First, the big pile.
Think of Dagen as a completely binary tree (this is actually inaccurate)
For A[i], the left son is a[i*2] right son for A[i*2+1]
Which means we already have a tree.
Then we fix each node from the back to the
Fix (x) is putting x where he's supposed to be.
The action is to compare X with its two child nodes
If x> his two nodes, the Exit function
If x< his two nodes,
Swap x with the maximum node y in his two nodes, and then fix (y)
If one of his child nodes is empty, set the value of this child node to-inf
After the pile is built, we can guarantee that the top element of the heap is the biggest.
So we put the top elements into the array, and then put the heap tail elements on top of the heap, and finally fix (1)
Repeat this process until the element in the heap is 0
Code:
I wrote this code a year ago, it's so ugly, please don't mind
#include <iostream>using namespacestd;intParentinti) {returni/2;}intLeft (inti) {returni*2;}intRight (inti) {returni*2+1;}voidMaintenance (int*a,intIintlen);voidSwap (int&a,int&B) {intS;s=a;a=b;b=s;return;}void inch(int*a,int&l);voidBuildint*a,intl);voidHeap_sort (int*a,intl);intMain () {inta[ the],l; inch(a,l); Build (a,l); Heap_sort (a,l); for(intk=1; k<=l;k++) cout<<a[k]<<" "; return 0;}void inch(int*a,int&l) { intI=1; while(Cin>>a[i]) i++; L=i-1; return;}voidMaintenance (int*a,intIintLen) { intL=left (i), r=right (i), large=0; if(L<=len&&a[i]<a[l]) large=l; ElseLarge=i; if(R<=len&&a[large]<a[r]) large=R; if(large==i)return; Swap (A[i],a[large]); Maintenance (A,large,len); return;}voidBuild (int*a,intl) { for(intk=l/2; k>=1; k--) Maintenance (a,k,l); return;}voidHeap_sort (int*a,intl) { for(intk=l;k>=1; k--) {Swap (a[1],a[k]); L--; Maintenance (A,1, L); } return;}
Heap Sort Review