After many advices, helps, I could eventually solve this problem myself, happy~~
All I did was to write a replacement function for strcmp() and then use a bubble sort function to sort input strings in lexicographical order.
Much simpler than nasty nested loops :P
my_strcmp():
In fact, I got the realization from the source code algorithm. The important part is that I understand how this algorithm works now.Code:int my_strcmp (char *str1, char *str2) { int id = 0; char *temp1, *temp2; temp1 = my_strlwr(str1); temp2 = my_strlwr(str2); while(!(id = *temp1 - *temp2) && *temp2) { ++temp1, ++temp2; } if (id < 0) { id = -1; } else if (id > 0) { id = 1; } return id; }
Below is the original problem:
Hi,
I want to write a function to perform lexicographical sorting using a simple bubble sort technique. So far I've got the basic code running, but something is not right. I can tell the algorithm is wrong but cannot fix it, please help.
Here is my function:
I've tried not to use the third inner loop, but then it will just perform the first letter comparison...And yes, let me stress that strcmp or strncmp should not be used...Code:int bubble_sort(char **words, int num_word) { int x, y, z; char *temp; for (x = 0; x < num_word; x++) { for (y = 0; y < (num_word-1); y++) { for (z = 0; z < (WORD_SIZE+1); z++) { if (words[y][z] < words[y+1][z]) { temp = words[y+1]; words[y+1] = words[y]; words[y] = temp; break; } else { continue; } } } } return 0; }
Thank you in advance.