Heap Sorting Algorithm

Source: Internet
Author: User

Heap Sorting Algorithm
/* Date: 2014.12.15
Heap Structure: it is a tree structure, which is exactly a binary tree. In this tree, each node corresponds to a record of the original data and meets the following conditions: 1. if the data is sorted in ascending order, the data of the non-leaf nodes must be greater than or equal to the data of the left and right subnodes. 2. if the data is sorted in ascending order, the data of non-leaf nodes must be smaller than or equal to the data of its left and right subnodes.
Heap sorting method: based on the method of selecting and sorting, The Heap Structure and binary tree are used to sort data.
Process: 1) construct a Heap Structure and sort the raw unordered data according to the definition of the previous Heap Structure;
2). Heap sorting output.
Time Complexity: The worst O (nlog2 (n) and average O (nlog2 (n )).
Space complexity: O (1 ).
It is an unstable sorting algorithm.

*/


Void HeapSort (int * arr, int n)

{
Int I, j, h, k, temp;


For (I = (n/2)-1; I> = 0; I --)
{
While (2 * I + 1 <n)
{
J = 2 * I + 1;
If (j + 1) <n)
{
If (arr [j] <arr [j + 1])
{
J ++;
}
}
If (arr [I] <arr [j])
{
Temp = arr [I];
Arr [I] = arr [j];
Arr [j] = temp;
I = j;
}
Else
{
Break;
}
}

}


Printf ("initialized to a large top heap :");

For (h = 0; h <n; h ++)
{
Printf ("% d", arr [h]);
}
Printf ("\ n ");

For (I = n-1; I> 0; I --)
{
Temp = arr [0];
Arr [0] = arr [I];
Arr [I] = temp;
K = 0;
While (2 * k + 1 <I)
{
J = 2 * k + 1;
If (j + 1) <I)
{
If (arr [j] <arr [j + 1])
{
J ++;
}
}
If (arr [k] <arr [j])
{
Temp = arr [k];
Arr [k] = arr [j];
Arr [j] = temp;
K = j;
}
Else
{
Break;
}
}

Printf ("the % d sorting result is:", n-I );
For (h = 0; h <n; h ++)
{
Printf ("% d", arr [h]);
}
Printf ("\ n ");
}

}



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.