Heap Sorting algorithm

Source: Internet
Author: User

/* date:2014.12.15
Heap structure: is a tree structure, exactly said to be a complete binary tree. In this tree, each node corresponds to a record of the original data, and meet the conditions: 1. If you order from small to large, the data of the non-leaf node is required to be greater than or equal to the data of its left and right child nodes; 2. If you sort from large to small, the data of the non-leaf node is required to be less than or equal to the data of its left and right child nodes.
Heap sorting idea: Based on the idea of the choice of sorting, using the heap structure and some properties of the two-fork tree to complete the data sorting.
Process: 1). Constructs the heap structure, the original disorderly data according to the front heap structure definition carries on the order;
2). heap sort output.
Time complexity: Worst O (nlog2 (n)), average O (nlog2 (n)).
Space complexity: O (1).
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 ("Initialize to large top heap for:");

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 result of order%d" is: ", n-i);
for (h = 0;h < N;h + +)
{
printf ("%d", arr[h]);
}
printf ("\ n");
}

}



Heap Sorting algorithm

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.