Skip to content

Commit 2ce3d3a

Browse files
authored
Merge pull request #177 from akashmodak97/heap-sort
Implemented heap sort in C
2 parents cd45143 + faac4d0 commit 2ce3d3a

File tree

1 file changed

+54
-1
lines changed

1 file changed

+54
-1
lines changed

heap_sort/clang/heap_sort.c

+54-1
Original file line numberDiff line numberDiff line change
@@ -1 +1,54 @@
1-
//add your code here
1+
#include <stdio.h>
2+
3+
int main()
4+
{
5+
int heap[10], n, i, j, c, root, temp;
6+
7+
printf("\nEnter no of elements :");
8+
scanf("%d", &n);
9+
printf("\nEnter the elements : \n");
10+
for (i = 0; i < n; i++){
11+
printf("Heap[%d] : ",i+1);
12+
scanf("%d", &heap[i]);
13+
}
14+
for (i = 1; i < n; i++)
15+
{
16+
c = i;
17+
do
18+
{
19+
root = (c - 1) / 2;
20+
if (heap[root] < heap[c]) /* creating MAX heap array */
21+
{
22+
temp = heap[root];
23+
heap[root] = heap[c];
24+
heap[c] = temp;
25+
}
26+
c = root;
27+
} while (c != 0);
28+
}
29+
30+
for (j = n - 1; j >= 0; j--)
31+
{
32+
temp = heap[0];
33+
heap[0] = heap[j]; /* swap max element with rightmost leaf element */
34+
heap[j] = temp;
35+
root = 0;
36+
do
37+
{
38+
c = 2 * root + 1; /* left node of root element */
39+
if ((heap[c] < heap[c + 1]) && c < j-1)
40+
c++;
41+
if (heap[root]<heap[c] && c<j) /* again rearrange to max heap array */
42+
{
43+
temp = heap[root];
44+
heap[root] = heap[c];
45+
heap[c] = temp;
46+
}
47+
root = c;
48+
} while (c < j);
49+
}
50+
printf("\nThe sorted array is : ");
51+
for (i = 0; i < n; i++)
52+
printf("\t %d", heap[i]);
53+
return 0;
54+
}

0 commit comments

Comments
 (0)