chore(C): add Heap-sort (#285)

pull/290/head
Ranu Singh 2021-05-08 22:34:14 +05:30 committed by GitHub
parent 10ca1dc40c
commit 5d0c19e8de
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 73 additions and 0 deletions

View File

@ -18,6 +18,7 @@
- [Bubble Sort](sorting/bubble-sort.c)
- [Merge Sort](sorting/merge-sort.c)
- [Insertion Sort](sorting/insertion-sort.c)
- [Heap Sort](sorting/heap-sort.c)
## Strings
- [Count Words](strings/count-words.c)

View File

@ -0,0 +1,72 @@
// Heap Sort in C
#include<stdio.h>
#include<conio.h>
void main()
{
int heap[10], no, i, j, c, root, temp;
printf("\n Enter no of elements :");
scanf("%d", &no);
printf("\n Enter the nos : ");
for (i = 0; i < no; i++)
scanf("%d", &heap[i]);
for (i = 1; i < no; i++)
{
c = i;
do
{
root = (c - 1) / 2;
if (heap[root] < heap[c]) /* to create MAX heap array */
{
temp = heap[root];
heap[root] = heap[c];
heap[c] = temp;
}
c = root;
} while (c != 0);
}
printf("\n Heap array : ");
for (i = 0; i < no; i++)
printf("%d\t ", heap[i]);
for (j = no - 1; j >= 0; j--)
{
temp = heap[0];
heap[0] = heap[j]; /* swap max element with rightmost leaf element */
heap[j] = temp;
root = 0;
do
{
c = 2 * root + 1; /* left node of root element */
if ((heap[c] < heap[c + 1]) && c < j-1)
c++;
if (heap[root]<heap[c] && c<j) /* again rearrange to max heap array */
{
temp = heap[root];
heap[root] = heap[c];
heap[c] = temp;
}
root = c;
} while (c < j);
}
printf("\n The sorted array is : ");
for (i = 0; i < no; i++)
printf("\t %d", heap[i]);
printf("\n Time Complexity : \n Best case = Avg case = Worst case = O(n logn) \n");
getch();
}
/* Test Case:-
Enter no of elements :5
Enter the nos:
10
23
2
1
90
Heap array : 90 23 2 1 10
The sorted array is : 1 2 10 23 90
Time Complexity:
Best case = Avg case = Worst case = O(n logn) */