1
\$\begingroup\$

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 ;
 }
 previous++;
 }
}
200_success
145k22 gold badges190 silver badges478 bronze badges
asked Apr 19, 2019 at 14:24
\$\endgroup\$

1 Answer 1

2
\$\begingroup\$

Portability
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().

Performance
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.

answered Apr 19, 2019 at 15:09
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.