0% found this document useful (0 votes)
42 views2 pages

Practical - 14: Write A Program To Implement Heap Sort

The document describes an implementation of heap sort in C. It takes in an array of numbers as input, rearranges the array into a max heap order, then repeatedly swaps the first and last elements and sifts them down to sort the array. The time complexity of the algorithm is O(n log n) in all cases.

Uploaded by

Anonymous
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
42 views2 pages

Practical - 14: Write A Program To Implement Heap Sort

The document describes an implementation of heap sort in C. It takes in an array of numbers as input, rearranges the array into a max heap order, then repeatedly swaps the first and last elements and sifts them down to sort the array. The time complexity of the algorithm is O(n log n) in all cases.

Uploaded by

Anonymous
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

SYIT3-A 160410116114

Practical - 14
Write a program to implement Heap Sort.

Heap Sort

Input :
#include <stdio.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("Heap array : ");


for (i = 0; i < no; i++)
printf("%d\t ", heap[i]);
for (j = no - 1; j >= 0; j--)
{
temp = heap[0];
SYIT3-A 190410116114

heap[0] = heap[j]; /* swap max element with rightmost leaf elem


ent */
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 Complexity : \n Best case = Avg case = Worst case = O(n lo
gn) \n");
}

Output :
Enter no of elements :5
Enter the nos : 11
12
13
14
15
Heap array : 15 14 12 11 13
The sorted array is : 11 12 13 14 15
Complexity :
Best case = Avg case = Worst case = O(n logn)

You might also like