Heap sort (max heap)

Source: Internet
Author: User
#include "iostream.h" using namespace std;//because I start from 0 #define LEFTCHILD (i) ((i) +1)//i-n range, create maximum heap void maxheap (int a[], int i, int N) {int tmp;int child;for (tmp=a[i]; Leftchild (i) <n;i=child) {child = Leftchild (i); if (Child!=n-1&&a[child+1]>a[child]) {child++;} if (Tmp<a[child]) {a[i]=a[child];} else break    ;} A[i]=tmp;} void heapsort (int a[], int N) {//Because 2*i does not exceed N, so I start from N/2 for (int i=n/2;i>=0;i--) {maxheap (a,i,n);} for (int i=n-1;i>0;i--) {//a[0] is the maximum value of the heap, in exchange, the maximum value of the heap is placed in the tail swap (a[0],a[i]);//Rebuild the maximum heap maxheap (a,0,i);}} int main (int argc, char *argv[]) {int n;cin>>n;int a[100];for (int i=0;i<n;i++) {cin>>a[i];} Heapsort (A,n); for (int i=0;i<n;i++) {cout<<a[i]<< "";} Cout<<endl;return 0;}

Heap sort (max heap)

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.