I’m trying to sort strings according to their names lexicographically.
so I have an array of structures
typedef struct buff{
char *name;
} structure;
and I’m copying names of files with their associated extensions. So that the content of that structure looks like s[0].name = "picture1.jpg" s[1].name = "DCP003.JPG" and stuff like that.
and I’m trying to sort that, and I’m unable to achieve that.. what I have so far is this.
void sort(structure *s, int counter){
for (int i = 0; i < counter - 1; i++){
for (int j = 0; j < counter - 1 - i; j++){
if (strcmp(s[j].name, s[j+1].name) > 0){
structure tmp;
tmp = s[j];
s[j] = s[j+1];
s[j+1] = tmp;
}
}
}
for (int i = 0; i < counter; i++){
printf("%d - %s\n", i+1, s[i].name);
}
}
and it doesn’t work as I want.. tried several versions still no good .. where am I making mistake? Any advice is greatly appreciated..
Try something like this:
Output: