Heap sort max_heapify tuning heap functions

Source: Internet
Author: User
Tags int size

A little time to study the heap sort, read the introduction to the algorithm, now record

The Max_heapify () function is a very important method in heap ordering.

#include <iostream> using namespace std; int a[15]={0,27,17,3,16,13,10,1,5,7,12,4,8,9,0}; int size=15; int length=15; int left (int i) {return i*2,} int right (int i) {return i*2+1;} int parent (int i) {return i/2;} void swap (int &a,int & b) {int tem=a;a=b;b=tem;}/* keeps the nature of the heap, the function verifies that it conforms to the nature of the maximum (small) heap, and adjusts its maximum (small) heap with its child nodes as the root node if it is not satisfied, ultimately keeping the heap still a maximum (small) heap. void max_heapify (int *a,int i) {int l=left (i), r=right (i), largest; if (L<=size&&a[l]>a[i]) largest=l; else Largest =i; if (R<=size&&a[r]>a[largest]) largest=r; if (largest!=i) {swap (a[largest],a[i]); max_heapify (a,largest);}} void max_heapify2 (int *a,int i)//iterative method {int l,r,largest; for (int j=i;j<size;) {l=left (j), R=right (j); if (l<size& &r<size) {if (a[j]<a[l]) largest=l; else largest=j; if (a[largest]<a[r]) largest=r; if (largest!=j) swap (a[ LARGEST],A[J]), j=largest; else return; }else {if (l<=size&&a[l]>a[j]) swap (a[j],a[l]), if (R<=size&&a[r]>a[j]) swap (A[j],a[r]); Return }}} int main () {for (int i=1;i<length;i++) cout<<a[i]<< ""; cout<<endl; Max_heapify (a,3);//Call function for (int i=1;i<length;i++) cout<<a[i]<< ""; cout<<endl; Return 0; 

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.