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 ");
}
}