I know there are some post about bubblesorting a 2d array in C, but my problem is a little strange as it only occurs with ascending sorting while descending sorting works just fine (and both those algorithms are completely analogical).The only thing I noticed was that ascending sorting printed only a half of each "word".
My program is supposed to bubblesort strings of characters separated with white signs that can be read from standard input or from a file.Reading from standard input is finished with entering a single dot and reading from file ends at EOF.
The code looks like this:
int main()
{ FILE *plik=NULL;
int i,j;
int k,l;
int m;
int a,b;
char tym;
char odp;
char ans;
char c;
char tab[100][100];
char nazwa[100];
printf("Would you like to sort from a file?(Y/N)\n");
scanf("%s",&odp);
if(odp=='n' || odp=='N')
{printf("Enter character strings and finish with a DOT:\n");
getc(stdin);
i=0;
j=0;
while(1)
{c=getc(stdin);//reading from stdin
if(c!='\n' && c!='\t' &&c!=' ')
{tab[i][j]=c;
if(tab[0][j]=='.') //ending input
{tab[0][j]='\0'; //clearing the extra sign
break;}
i++; //columns counter
printf("%c",c);}
else
{i=0;
j++; //row counter
printf("\n");}}}
else if(odp=='y' || odp=='Y')
{printf ("Enter the file's name:\n");
scanf("%99s",&nazwa);
plik = fopen(nazwa,"rt");
if(plik==NULL)
{printf("\nFailed reading from file : %s \n\n",nazwa); //jesli blad odczytu przerwij dzialanie
printf("Check the file and try again \n");
fclose(plik);
return 0;}
else
{i=0;
j=0;
do
{c=getc(plik);
if(c!='\n' && c!='\t' &&c!=' ')
{tab[i][j]=c;
i++; //columns counter
printf("%c",c);}
else
{i=0;
j++; //rows counter
printf("\n");}}
while(c!=EOF);} //ending reading
} fclose(plik);
//Here starts the sorting
printf("\nSelect sorting order (A/D)\n");
scanf("%s",&ans);
if(ans=='a' || ans=='A') //ascending
{for(m=0;m<j;m++) //moving to next rows
for(k=0;tab[k][m]!='\0';k++)//later as in a typical bubblesort
for(l=0;l<100-1-k;l++)
if(tab[l][m] > tab[l+1][m])
{tym = tab[l+1][m];
tab[l+1][m] = tab[l][m];
tab[l][m] = tym;}}
else if (ans=='D' || ans=='d') //descending
{for(m=0;m<j;m++) //moving to next rows
for(k=0;tab[k][m]!='\0';k++) //later as in typical bubblesort, analogically to ascending order
for(l=0;l<100-1-k;l++)
if(tab[l][m] < tab[l+1][m])
{tym = tab[l+1][m];
tab[l+1][m] = tab[l][m];
tab[l][m] = tym;};}
//returning results
a=0;
b=0;
while(b<j)
{if (tab[a][b]!='\0')
{putchar(tab[a][b]);
a++;}
else
{a=0;
b++;
printf("\n");}
}
return 0;
}
I am sorry for my English and mess in the code, but I started programming just a month ago. I would be very greatful if someone could help me with this problem. Thank You for Your time :)