C program for implementing Heap Sort Algorithm for sorting a given list of integers in ascending order

Estudies4you

1 //c program to implement heap sort
2 #include<stdio.h>
3 void adjust(int a[],int i,int n);
4 void heapify(int a[],int n);
5 void heapsort(int a[],int n);
6 //BEGIN MAIN
7 void main()
8 {
9 int n,a[10],i;
10 printf("enter size of an array");
11 scanf("%d",&n);
12 printf("enter elements");
13 for(i=1;i<=n;i++)
14 {
15 scanf("%d",&a[i]);
16 }
17 heapsort(a,n);
18 printf("the elements in sorted order are:\n");
19 for(i=1;i<=n;i++)
20 {
21 printf("-> %d ",a[i]);
22 }
23 }//END OF MAIN
24 //implementation of function adjust
25 void adjust(int a[],int i,int n)
26 {
27 int j=2*i;
28 int item=a[i];
29 while(j<=n)
30 {
31 if((j<n)&&(a[j]<a[j+1]))
32 ++j;
33 if(item>=a[j])
34 break;
35 else
36 {
37 a[j/2]=a[j];
38 j=2*j;
39 }
40 }
41 a[j/2]=item;
42 }
43 //implementation of function heapify
44 void heapify(int a[],int n)
45 {
46 int i;
47 for(i=n/2;i>=1;i--)
48 adjust(a,i,n);
49 }
50 //implementation of HEAPSORT
51 void heapsort(int a[],int n)
52 {
53 int i;
54 heapify(a,n);
55 for(i=n;i>=2;i--)
56 {
57 int temp=a[i];
58 a[i]=a[1];
59 a[1]=temp;
60 adjust(a,1,i-1);
61 }
62 }
63
64 OUPUT:
65 enter size of an array5
66 enter elements25
67 36
68 14
69 26
70 21
71 the elements in sorted order are:
72 -> 14 -> 21 -> 25 -> 26 -> 36
To Top