Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Create HeapSort #213

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
52 changes: 52 additions & 0 deletions HeapSort
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
#include<stdio.h>
#include<conio.h>
void swap(int *x,int *y)
{
int temp;
temp=*x;
*x=*y;
*y=temp;
}
void heapify(int arr[],int n,int i)
{ //initial largest as root
int largest=i;
int l=(2*i)+1;//left
int r=(2*i)+2;//right
//left child is greater han right child
if(l<n &&arr[l] >arr[largest])
largest=l;
//right child is greater han left child
if(r<n &&arr[r] >arr[largest])
largest=r;
if(largest!=i) //if largest is not root
{
swap(& arr[i],& arr[largest]);
//recursively heapify the affected subtree
heapify(arr,n,largest);
}
}
void heapsort(int arr[],int n)
{
int i;
//build heap(rearrange array)
for(i=(n/2)-1;i>=0;i--)
heapify(arr,n,i);
for(i=n-1;i>0;i--) //one by one extract element from heap
{
swap(&arr[0],&arr[i]); //move curr to end
heapify(arr,i,0); //calling max heapify on reduced heapify
}
}
int main()
{
int arr[10],i,n;
printf("Enter number of elements to be sorted:\t");
scanf("%d",&n);
printf("Enter the element\n");
for(i=0;i<n;i++)
scanf("%d",&arr[i]);
heapsort(arr,n);
printf("Sorted Array ");
for(i=0;i<n;i++)
printf("%d ",arr[i]);
}