Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I correctly sort strings in C?

Tags:

c

string

sorting

Here is my code:

#include <stdio.h>
#include <string.h>
#include <errno.h>

int cmp(const void *a, const void *b) {
    const char **ia = (const char **)a;
    const char **ib = (const char **)b;
    return strcmp(*ia, *ib);
}

void print_array(char **array, size_t len) {
    size_t i;
    for(i=0; i<len; i++) {
        printf("%s, ", array[i]);
    }
    putchar('\n');
}

int main(int argc, char *argv[]) {

        char *strings[] = { "z1.doc", "z100.doc",  "z2.doc", "z3.doc", "z20.doc"};
        size_t strings_len = sizeof(strings) / sizeof(char *);
        print_array(strings, strings_len);
        qsort(strings, strings_len, sizeof(char *), cmp);
        print_array(strings, strings_len);

        system("PAUSE");
        return 1;
}

the actual output is

z1.doc, z100.doc, z2.doc, z20.doc, z3.doc

and I want it to be

z1.doc, z2.doc, z3.doc, z20.doc, z100.doc

What am doing wrong?

like image 699
netdur Avatar asked Dec 19 '25 08:12

netdur


2 Answers

The actual output is correct, the string "z100.doc" is less than "z2.doc". The strcmp compares character by character and when it gets to the '1' that is less than '2' and it stops there, so z100 < z2.

If you name the files z001.doc, z002.doc, z003.doc, z020.doc, z100.doc it will sort the way you want.

like image 118
progrmr Avatar answered Dec 21 '25 20:12

progrmr


Change your comparator to say:

return (atoi(*ib + 1) - atoi(*ia + 1));
like image 29
Dan Avatar answered Dec 21 '25 20:12

Dan