1. Heap Sorting
The definition of heap sort and thought can refer to Baidu Encyclopedia: Heap Sort
In a nutshell, heap sequencing is an improved sort of selection, the improvement is that each time you make a choice, not only the largest number of the selection, but also the sorting process of some of the operations recorded, so in the subsequent sort can be used, and the idea of grouping in the inside, thereby improving the sorting efficiency, Its efficiency is O (N*LOGN).
2. Source Code
There are two core operations in the heap sort, one is to create a large top heap (or a small top heap, here is a large heap), and one is to adjust the heap. Note here that there is no real build heap, just take advantage of the complete binary tree feature, it corresponds to the subscript of the array (for example, for node I, if there is a left child and a right child, the subscript must be 2*i, and 2*i+1) where the creation is created from the bottom up, and the adjustment is from the top down.
Here for convenience, the heap starts from the a[1] position.
The results of the code run are as follows:
The source code is as follows:
#include <stdio.h> int c=0; The function of the/*heapadjust () function is to adjust the data from a[m] to A[n] to meet the characteristics of the large top heap * */*a[] is an array to be processed, M is the starting coordinate, n is the ending coordinate/void heapadjust (int a[], int m, int
n) {int I, temp;
TEMP=A[M];
for (i=2*m;i<=n;i*=2)//starting from the left child of M {if (i+1<=n && a[i]<a[i+1])//If the left child is small Yu Yu child, then i++, so I is the value of the eldest child's subscript value
{i++;
if (a[i]<temp)//If the eldest child is less than the temp, do nothing, exit the loop, otherwise swap the value of a[m] and A[i], and place the maximum value at A[i] {break;
} A[m]=a[i];
M=i;
} a[m]=temp;
} void Crtheap (int a[], int n)//initialize creates a large top heap {int i;
for (I=N/2; i>0; i--)//N/2 is the last parent node, and then the large top heap {heapadjust (A, I, N) is set forward;
The role of the/*swap () function is to convert a[i] and a[j] swaps */void swap (int a[], int i, int j) {int temp;
Temp=a[i];
A[I]=A[J];
A[j]=temp;
C + +;
} void Heapsort (int a[], int n) {int i;
Crtheap (A, n); For (i=n i>1; i--) {swap (A, 1, i);//The largest number in the first number, that is, from A[1 to A[i], to the a[i position Heapadjust (A, 1, i-1);//to the remaining a[1] to a[i], heap sort again, select the maximum value, and place the a[1] in the position of} int main (void) {int i;
int a[10]={-1,5,2,6,0,3,9,1,7,4};
printf (before "sort:");
for (i=1;i<10;i++) {printf ("%d", a[i]);
} heapsort (A, 9);
printf ("N/a total exchange of data%d times \ n", c);
printf ("After sort:");
for (i=1;i<10;i++) {printf ("%d", a[i]);
printf ("\n\n\n");
return 0;
}