C program to Implement Heap Sort of Names using file

Implement Heap Sort of Names using file


#include<stdio.h>
#include<conio.h>
#define MAX 20
char na[MAX][MAX];
void heap (int);
void upper(char *s)
{
int i;
for(i=0;(s[i]!='\0')&&(s[i]!='\n');i++)
if((s[i]>='a')&&(s[i]<='z'))
s[i]=s[i]-32;
}
void heap_sort(int n)
{
char tmp[MAX];
int i,l,r,j;
while(n>2)
{
for(i=0;na[0][i]!='\0'||na[n][i]!='\0';i++)
{
tmp[i]=na[n][i];
na[n][i]=na[0][i];
na[0][i]=tmp[i];
}
for(i=0;na[l][i]!='\0'||na[r][i]!='\0';i++)
{
l=2*i+1;
r=2*i+2;
if(na[l][i]>na[r][i]&&na[l]                                [i]>na[0][i])
for(j=0;na[r][j]!='\0'||na[0][j]!='\0';j++)
{
tmp[j]=na[l][j];
na[l][j]=na[0][j];
na[0][j]=tmp[j];
}
else if(na[r][i]>na[l][i]&&na[r][i]>na[0][i])
for(j=0;na[r][j]!='\0'||na[0][j]!='\0';j++)
{
tmp[j]=na[r][j];
na[r][j]=na[0][j];
na[0][j]=tmp[j];
}
n--;
heap(n);
break;
}
}
while(n==2)
{
for(i=0;na[0][i]!='\0'||na[n][i]!='\0';i++)
{
tmp[i]=na[n][i];
na[n][i]=na[0][i];
na[0][i]=tmp[i];
}
for(i=0;na[0][i]!='\0'||na[1][i]!='\0';i++)
{
tmp[i]=na[1][i];
na[1][i]=na[0][i];
na[0][i]=tmp[i];
}
n--;
}
}
void heap(int n)
{
int i,j,p,k;
char tmp[MAX];
for(i=1;na[i-1][0]!='\n'&&i<n;i++)
{
p=(i-1)/2;
for(j=0;na[i][j]!='\0';j++)
{
if(na[p][j]<na[i][j])
{
for(k=0;na[i][k]!='\0'||na[p][k]!='\0';k++)
{
tmp[k]=na[i][k];
na[i][k]=na[p][k];
na[p][k]=tmp[k];
}
i=p-1;
}
break;
}
}
}
void main()
{
FILE *f;
int i,a;

clrscr();

f=fopen("c:/name.txt","r");
if(f==NULL)printf("invalid");
else printf("valid");
       printf("FILE ELEMENTS:\n\n");
for(i=0;na[i-1][0]!='\n';i++)
{
fgets(na[i],20,f);
upper(na[i]);
printf("\n%s",na[i]);
}
heap(i);
printf("HEAP ELEMENTS:\n\n");
for(i=0;na[i][0]!='\0';i++)
{
printf("\n%s",na[i]);
}
heap_sort(i-2);
printf("\nSORTED LIST:\n") ;
for(i=0;na[i][0]!='\0';i++)
printf("\n%s",na[i]);
getch();
}

File : c:/name.txt


SACHIN
YOUVI
GAUTHUM
DHONI
KOHLI





0 comments:

Post a Comment