# how to sort strings alphabetically?

This is a discussion on how to sort strings alphabetically? within the C Programming forums, part of the General Programming Boards category; hello everyone...I am just new in this forum.I am having problem in sorting C strings alphabetically...anyone please help!...

1. ## how to sort strings alphabetically?

hello everyone...I am just new in this forum.I am having problem in sorting C strings alphabetically...anyone please help!

2. For starters, take a look at qsort() from <stdlib.h> and strcmp() from <string.h>.

3. Well fundamentally when you compare two strings using strcmp(st1, st2), it returns -1, 0 or 1 depending on whether st1 is less, equal, or greater than st2 respectively. Whatever sort algorithm you implement, it will probably be based on comparing two elements at a time.

4. Originally Posted by nonoob
Well fundamentally when you compare two strings using strcmp(st1, st2), it returns -1, 0 or 1 depending on whether st1 is less, equal, or greater than st2 respectively. Whatever sort algorithm you implement, it will probably be based on comparing two elements at a time.
Technically, it doesn't have to be -1, 0 or 1, but rather "a negative, zero or a positive" value. Often, strcmp() returns (*st1 - *st2), which of course will not usually be -1 or 1 if st1 and st2 aren't equal.

--
Mats

5. Correct again.

6. This is for nonoob. Though I do believe he is a linux guy, in which case he doesn't get a string comparison function that returns -1, 0, or 1 as its only return values.

7. First of all, that one is int CompareString(), which requires who-knows-what header and linking headaches. No thanks. I stick with things that work and would write my own if I had to.

Then is says this curious thing:

To maintain the C run-time convention of comparing strings, the value 2 can be subtracted from a nonzero return value. Then, the meaning of < 0, ==0 and > 0 is consistent with the C run times.

Um. does that mean that natively it returns

3 - if the result indicates a > b
1 - if the result indicates a < b
0 - if the result indicates a == b

That way, when you subtract 2 from the non-zero results, you get 1 and -1 respectively.

8. If you include windows.h you can have that function. I thought those values were -1,0, and 1. My bad. I just use the macros that the docs say to use when comparing. It is a windows specific thing and I thought I would mention it for the sake of personal growth. Or whatever you want to call it.