0% found this document useful (0 votes)
7 views1 page

Program6 Heapsort

The document provides a C program that implements the heap sort algorithm to sort an array of numbers in ascending order. It includes functions for swapping elements, heapifying the array, and performing the heap sort. The main function prompts the user for the size and elements of the array, sorts them, and then displays the sorted elements.

Uploaded by

Amar A
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)
7 views1 page

Program6 Heapsort

The document provides a C program that implements the heap sort algorithm to sort an array of numbers in ascending order. It includes functions for swapping elements, heapifying the array, and performing the heap sort. The main function prompts the user for the size and elements of the array, sorts them, and then displays the sorted elements.

Uploaded by

Amar A
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

5. Write a C program to sort the numbers in ascending order using heap sort.

#include<stdio.h>

void swap( int *a, int *b)


{
int temp=*a;
*a=*b;
*b=temp;
}
void heapify( int a[],int n, int i)
{
int largest=i;
int left=2*i+1;
int right=2*i+2;
if( left < n && a[left] > a[largest])
largest=left;
if(right < n && a[right] > a[largest])
largest=right;
if( largest!=i)
{
swap(&a[i],&a[largest]);
heapify(a,n,largest);
}
}
void heapsort(int a[],int n)
{
int i;
for(i=n/2-1;i>=0;i--)
heapify(a,n,i);
for(i=n-1;i>=0;i--)
{
swap(&a[0],&a[i]);
heapify(a,i,0);
}
}
void main()
{
int a[100],n,i;
printf(" Enter array size\n");
scanf("%d", &n);
printf("Enter array elements\n");
for(i=0;i<n;i++)
scanf("%d", &a[i]);
heapsort(a, n);
printf("sorted elements are\n");
for(i=0;i<n;i++)
printf("%d\t", a[i]);

You might also like