4-5 heapsort.c
1#include <stdio.h>2#include"4-1 createdata.c"3 #defineArraylen 104 voidHeapadjust (intA[],intSintN//Composition Heap5 {6 intj,t;7 while(2*s+1<n)//The first s node has a right subtree.8 {9j=2*s+1 ;Ten if((j+1) <N) One { A if(a[j]<a[j+1])//Right- left subtree is smaller than right subtree, you need to compare right sub- tree -j + +;//increase the number by 1, point to right sub-tree - } the if(A[s]<a[j])//compare the numbers of S and J - { -T=a[s];//Exchanging Data -a[s]=A[j]; +a[j]=T; -S=j;//the heap is destroyed and needs to be re-adjusted + } A Else //compare left and right children are large heap is not destroyed, no longer need to adjust at Break; - } - } - voidHeapsort (intA[],intN//Heap Sort - { - intt,i; in intJ; - for(i=n/2-1; i>=0; i--)//build a[0,n-1] into a large heap to Heapadjust (A, I, n); + for(i=n-1;i>0; i--) - { thet=a[0];//exchange with the first record *a[0] =A[i]; $A[i] =T;Panax NotoginsengHeapadjust (A,0, i);//Resize a[0] to a[i] to the heap - } the } + intMain () A { the intI,a[arraylen]; + for(i=0; i<arraylen;i++) -a[i]=0; $ if(! Createdata (A,arraylen,1, -)) $ { -printf"generate random number unsuccessful!\n"); - getch (); the return 1; - }Wuyiprintf"Original data:"); the for(i=0; i<arraylen;i++) -printf"%d", A[i]); Wuprintf"\ n"); - Heapsort (A,arraylen); Aboutprintf"after sorting:"); $ for(i=0; i<arraylen;i++) -printf"%d", A[i]); -printf"\ n"); - getch (); A return 0; +}
4.5 Heap Sorting method