Classical sorting algorithm--heap sort

Source: Internet
Author: User

for an int array. Please write a heap sorting algorithm. Sorts the array elements.

Given an int array a and the size of the array n, return the sorted array.

Test examples:
[1,2,3,5,2,3],6

[1,2,2,3,3,5]


Class Heapsort {public:int* heapsort (int* A, int n) {        buildmaxheap (A, n);//First build the array A into a large top heap for        (int i = n-1; i > = 1; i--) {            swap (a[0],a[i]);//Exchange Maxheapfix (A, 0, i-1) with the top maximum of the heap and the last number that is not sorted;//Will a[0,i-1] again adjust to the big top heap}return A;        Constructs A large top heap void buildmaxheap (int *a, int n) {for (int i = N/2-1; I >= 0; i--) maxheapfix (A, I, n-1);}        Resize again to a large top heap void maxheapfix (int *a, int i, int n) {int key = a[i];for (int j=2*i;j<n;j*=2) {if (J<n && a[j]<a [J+1]) Find out the larger ++j;if (Key>=a[j])//root node key and the larger value in the left and right sub-tree. If the key is larger, then jump out of the loop directly, if the key is small, then swap break; A[i] = a[j];i=j;} A[i] = key;}};


Classical sorting algorithm--heap sort

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.