C-PROGRAM HEAP SORT
#include<stdio.h> #include<stdlib.h> void heapify1(int *a, int lim) {int i,j,tmp,left,right,fg=0; i=1; while(fg==0){ left=2*i; right=(2*i)+1; if(right<=lim) { if(a[i]<a[left] || a[i]< a[right]){ if(a[left]>a[right]){ tmp=a[left]; a[left]=a[i]; a[i]=tmp; i=left; } else { tmp=a[right]; a[right]=a[i]; a[i]=tmp; i=right; }} else {fg=1;} }else if (left<=lim){ if(a[left]>a[i]){ tmp=a[left]; a[left]=a[i]; a[i]=tmp; i=left; } else{ fg=1; } }// end of left<=lim else{ //printf("Finished"); fg=1; } } printf("\nAfter heapifyng lim=%d\n",lim); for(j=1;j<=lim;j++) {printf("\t %d",a[j]);} }
{
int tmp;
do
{
tmp = a[1];
a[1]=a[lim];
a[lim]=tmp; lim=lim-1;
heapify1(a,lim);
}while(lim>1);
}
int main()
{
int a[20],i,lim,j,tmp;
printf("Enter total no. of elements: ");
scanf("%d", &lim);
for(i=1;i<=lim;i++)
{
printf("\n Enter element: ");
scanf("%d",&a[i]); j=i;
while( (j>1) && (a[j] > a[j/2] ))
{
tmp=a[j];
a[j]=a[j/2];
a[j/2]=tmp; j=j/2;
printf("hello"); }
//printf("welcome\n");
}
printf("\n After creation\n");
for(j=1;j<=lim;j++)
{
printf("\t %d ",a[j]);
}
heapsort1(a,lim);
printf("\n After heap sort\n");
for(i=1;i<=lim;i++)
{
printf("\t %d",a[i]);
}
printf("\n");
}
C Tutorial For beginners
Comments
Post a Comment