1 #include<stdio.h>
2 #define MAX 10
3 #define RANDOM(x) rand()%x
4 swap(int *a,int*b)
5 {
6 int tmp;
7 tmp=*a;
8 *a=*b;
9 *b=tmp;
10 }
11 void heapify(int *arr,int size,int i)
12 {
13 int largest=i,left=i*2,right=(i*2)+1;
14 if (left<size&&arr[left]>arr[i])
15 {
16 largest=left;
17 }
18 else
19 {
20 largest=i;
21 }
22 if (right<size&&arr[right]>arr[largest])
23 {
24 largest=right;
25 }
26 if(largest!=i)
27 {
28 swap(&arr[i],&arr[largest]);
29 heapify(arr,size,largest);
30 }
31 }
32
33 void build_heap(int *arr,int size)
34 {
35 int i;
36 for(i=size/2;i>=0;i--)
37 {
38 heapify(arr,size,i);
39 }
40 }
41
42 heap_sort(int *arr,int size)
43 {
44 int i;
45 build_heap(arr,size);
46 for(i=size-1;i>=1;i--)
47 {
48 swap(&arr[0],&arr[i]);
49 size-=1;
50 heapify(arr,size,0);
51 }
52 }
53
54 int main()
55 {
56 int i,arr[MAX+1];
57 //arr[]={4,1,3,2,16,9,10,14,8,7};
58 srand(time(0));
59 for(i=0;i<MAX;i++)
60 {
61 arr[i]=RANDOM(100);
62 printf("%d ",arr[i]);
63 }
64 printf("\n");
65 heap_sort(arr,MAX);
66
67 for(i=0;i<MAX;i++)
68 {
69 printf("%d ",arr[i]);
70 }
71 printf("\n");
72 }