October 21, 2015

MERGING SORTED WORDS C PROGRAM

merge sort program, merge sorting, merging sort, merge sort function, merge sort source code, merge sort array 

MERGING SORTED WORDS C PROGRAM 


#define ROWS 30
#define COLS 100
#define DBLROWS 60 //Double the rows
#define MAX 100
#include<stdio.h>
#include<string.h>
int main()
{
FILE *f1=fopen("words1.txt","r");
FILE *f2=fopen("words2.txt","r");
FILE *f3=fopen("mergedwords.txt","w");
char strings1[ROWS][COLS],strings2[ROWS][COLS],temp[MAX],strings3[DBLROWS][COLS];
int i,j,m=0,n=0,k=0;
while(fscanf(f1,"%s",strings1[m])==1)
m++;
while(fscanf(f2,"%s",strings2[n])==1)
n++;
printf("\nContents of first file is\n");
fprintf(f3,"\nContents of first file is\n");
for(i=0;i<m;i++)
{
printf("%s\n",strings1[i]);
fprintf(f3,"%s\n",strings1[i]);
}
printf("\nContents of second file is \n");
fprintf(f3,"\n\nContents of second file is \n");
for(j=0;j<n;j++)
{
printf("%s\n",strings2[j]);
fprintf(f3,"%s\n",strings2[j]);
}
fcloseall();

//Sorting contents of first file(Bubble Sort Algorithm)
for(i=0;i<m;i++)
{
for(j=0;j<m-i-1;j++)
{
if(strcmp(strings1[j],strings1[j+1])>0)
{
strcpy(temp,strings1[j]);
strcpy(strings1[j],strings1[j+1]);
strcpy(strings1[j+1],temp);
}
}
}
printf("\nSorted Contents of first file is\n");
fprintf(f3,"\nSorted Contents of first file is\n");
for(i=0;i<m;i++)
{
printf("%s\n",strings1[i]);
fprintf(f3,"%s\n",strings1[i]);
}

//Sorting contents of Second file(Bubble Sort Algorithm)
for(i=0;i<n;i++)
{
for(j=0;j<n-i-1;j++)
{
if(strcmp(strings2[j],strings2[j+1])>0)
{
strcpy(temp,strings2[j]);
strcpy(strings2[j],strings2[j+1]);
strcpy(strings2[j+1],temp);
}
}
}
printf("\nSorted Contents of Second file is \n");
fprintf(f3,"\n\nSorted Contents of Second file is \n");
for(i=0;i<n;i++)
{
printf("%s\n",strings2[i]);
fprintf(f3,"%s\n",strings2[i]);
}

//Merging code start
if(strcmp(strings1[m-1],strings2[n-1])>0)
strcpy(strings2[n],strings1[m-1]);
else
strcpy(strings1[m],strings2[n-1]);

i=j=0;
for(k=0;k<m+n;k++)
{
if(strcmp(strings1[i],strings2[j])>0)
{
strcpy(strings3[k],strings2[j]);
j++;
}
else
{
strcpy(strings3[k],strings1[i]);
i++;
}
}
//Merging code ends
printf("\n\nMerged array is \n");
fprintf(f3,"\n\nMerged array is \n");
for(k=0;k<m+n;k++)
{
printf("%s\n",strings3[k]);
fprintf(f3,"%s\n",strings3[k]);
}
fcloseall();
return(0);
}



No comments:
Write comments