How do I go about sorting a 2-D string array in C using bubble sort (or any other kind of sorting in that matter) ? What I'm actlly trying to do is as follows :
Example:
Unsorted 2-D string array :
abfg
abcd
xyzw
pqrs
orde
Sorted 2-D string array:
abcd
abfg
orde
pqrs
xyzw
My current algorithm which is not working (gives me an incompatibility error) is as follows :
#include <stdio.h>
#include<string.h>
int main()
{
char str[5][4];
int i,j;
char temp[4];
for (i=0;i<5;i++)
{
scanf("%s",str[i]);
}
for(i = 0; i<5-1; i++)
{
for(j = 0; j<5-1; j++)
{
if(strcmp(str[j],str[j+1])== -1)
{
temp = str[j];
str[j] = str[j+1];
str[j+1] = temp;
}
}
}
for(i = 0; i< 5; i++)
printf("%s ", str[i]);
return 0;
}
Arrays are not assignable as you're attempting in C. You need to setup some buffer swapping logic. For example.
if(strcmp(str[j+1],str[j]) < 0) // note: fixed.
{
strcpy(temp, str[j]);
strcpy(str[j], str[j+1]);
strcpy(str[j+1], temp);
}
Other issues with your code:
char[5]
to hold four-char strings (including space for the terminator)."%3s"
, which would have hinted your dimensions were too short to begin with.scanf
Anyway, all of that is related to your code, but not the question you posted. It is worth looking at regardless.
Best of luck.