What do you think of this bubble sorting function in C, for a string array? I would like to improve the readability, performance, and any good practices.

void         sort_entries(char **entries, int reverse)
    char     **next;
    char     **previous;
    char     *t;
    int      value;

    previous = tab;
    while (*(next = previous + 1))
        value = strcasecmp(*previous, *next);
        if ((!reverse && value > 0)
            || (reverse && value < 0))
            t = *previous;
            *previous = *next;
            *next = t;
            previous = entries;
            continue ;

The function strcasecmp() is a POSIX standard and not a in the C programming standard as pointed out in this stack overflow question. Therefore the sort_entries() function may not compile or link on some systems. It would be better if the program that contained the sort_entries() function also contained a version of strcasecmp().

Generally a bubble sort will be implemented as nested loops, the inner loop going over the whole input list to perform as many swaps as possible in a single pass. This implementation restarts at the beginning after a single swap requiring more passes. There is no performance improvement by this single loop over the nested loop implementation, and there may be a performance hit.

If the code swapped the pointers rather than the strings themselves there might be an improvement in the performance.

Variable Scope
It is better from a maintainability perspective and overall code comprehension to create variables as needed rather than create all the variables at the top of the function. It would be better if the variables t, next and value were defined within the loop rather than at the top of the function. The variables t and next are only needed within the if statement.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.