Originally Posted by
porstart
i'm trying to sort an array of strings which I have declared globally. Each string is a number following by a word (e.g. 14 socks). I'm just interested in sorting by number as of now.
I've tried two different sorting techniques, and both compile and run but nothing gets sorted. Here's my code for one technique (the other technique is a selection sort):
Code:
char global[500][15];
char buff1[128]; //local
Code:
for (i=0;i<place;i++)
for (j=0;j<place;j++) //place is the number of elements in the array of strings
{
if(strcmp(global[i], global[j]) > 0) {
strcpy(buff1, &global[i][12]);
strcpy(&global[i][12], &global[j][12]);
strcpy(&global[j][12], buff1);
}
}
Is there something I'm missing?
I also know I can use qsort, but since I'm unfamiliar with that I'd prefer something that involves using a swap, like what I have above.
The most common problem is caused by the "invisible" char's: '\n' and '\0', being the newline and end of string char, respectively.
You WANT the '\0' there, or else you just have a bunch of char's, and no string is in sight. You do NOT want the newline. So before any sorting, let's remove the newline:
Code:
len = strlen(Global[i]; //include <string.h> if you don't have it already included
if(Global[len-1] == '\n')
Global[len-1] = '\0'; //overwriting and shortening the string one char's worth
Note that strcmp is not sorting "by numbers". It sorts only according to the entire string (which here, should be what you want).
Then let's give your substitution sort, a bit more zip, and get rid of these 12's:
(Why the 12's??).
Code:
for (i=0;i<place-1;i++)
for (j=i+1;j<place;j++) //place is the number of elements in the array of strings
{
if(strcmp(global[i], global[j]) > 0) {
strcpy(buff1, global[i]);
strcpy(global[i], global[j]);
strcpy(global[j], buff1);
}
}
Global[i] is the address of the string at Global[i], so no & (ampersand), is needed for it. In C, 2D arrays are simply "arrays of arrays".
Try that. Please copy and paste the entire code above, because the innards of the sort, have been changed, as well.