Heap sort in C.

 

01 #include<stdio.h>
02
03 int main()
04 {
05 int b[10],no,i,j,c,p,temp;
06 printf("nn Enter no of elements..");
07 scanf("%d",&no);
08 printf(" Enter the nos..");
09
10 for(i=0; i<no; i++)
11 scanf("%d",&b[i]);
12 for(i=1; i<no; i++)
13 {
14 c=i;
15 do
16 {
17 p=(c-1)/2;
18 if(b[p]<b[c])
19 {
20 temp=b[p];
21 b[p]=b[c];
22 b[c]=temp;
23 }
24 c=p;
25 }
26 while(c!=0);
27 }
28 for(j=no-1; j>=0; j--)
29 {
30 temp=b[0];
31 b[0]=b[j];
32 b[j]=temp;
33 p=0;
34 do
35 {
36 c=2*p+1;
37 if((b[c]<b[c+1]) && c<j-1)
38 c++;
39 if(b[p]<b[c] && c<j)
40 {
41 temp=b[p];
42 b[p]=b[c];
43 b[c]=temp;
44 }
45 p=c;
46 }
47 while(c<j);
48 }
49 printf(" The sorted nos are..");
50 for(i=0; i<no; i++)
51 printf("%d ",b[i]);
52
53 return 0;
54 }
 
 
OUTPUT :

Enter no of elements..5
Enter the nos..
12
22
14
11
9

The sorted list is : 9 11 12 14 22

Related Post

Leave a Reply

Your email address will not be published. Required fields are marked *