Heap Sort Review

Source: Internet
Author: User

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&AMP;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

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.