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.c #869

Open
wants to merge 1 commit into
base: master
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
111 changes: 111 additions & 0 deletions C/heapsort.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
#include<stdio.h>













void heapify(int arr[],int n, int i)
{
int q;
int largest=i;
int left=2*i+1;
int right= 2*i+2;



if(left<n && arr[left]>arr[largest])
{
largest=left;
}


if(right<n && arr[right]>arr[largest])
{
largest=right;
}

if(largest!=i)
{
q=arr[i];
arr[i]=arr[largest];
arr[largest]=q;
heapify(arr,n, largest);
}


}



void heapsort(int arr[],int n)
{
int i,q;



for(i=(n/2)-1;i>=0;i--)
{

heapify(arr,n,i);
}

for(i=n-1;i>0;i--)
{

q=arr[0];
arr[0]=arr[i];
arr[i]=q;
heapify(arr,i,0);
}


}




void print(int arr[],int n)
{
int i;
for(i=0;i<n;i++)
{
printf("%d ",arr[i]);
}

printf("\n");
}



int main()
{
int arr[200000];

int n,i;
printf("Enter the size of array:");
scanf("%d",&n);


for(i=0;i<n;i++)
{
scanf("%d",&arr[i]);
}



heapsort(arr,n);



print(arr,n);
}