What does it mean to numerically sort alpha characters in opposite of lexicographic, like in K&R 5-14 with option -n
-
My guess would go for sorting on the ascii value, but that doesn't make much sense if you only have the alpha characters (from 'a' to 'z and 'A' to 'Z'), since it will be equivalent to their lexicographical ordering... – Xeo May 17 '11 at 20:14
-
@Mohamed, it's section 5-14 of *The C Programming Language*, by Brian Kernighan and Dennis Ritchie, commonly known as K&R. That's confirmed by the fact that section 5-14 is an exercise instructing the reader to change the way the `-n` option is applied to fields in the sorting program illustrated in chapter 5. – Rob Kennedy May 17 '11 at 20:17
-
Hahahaha!! Ok, I get it. Thanks @Rob. – Mohamed Nuur May 17 '11 at 20:18
2 Answers
It means to treat a string as a single numeric value instead of as a series of characters that happen to be numeric. K&R shows you the numcmp
function to use just above exercise 5-14. It converts the char*
arguments to double
and compares them numerically, instead of comparing the strings one character at a time. That way, the string 103
gets sorted after the string 23
because 103 is greater than 23. Comparing as strings, 103
would sort ahead of 23
because the character code for 1
is less than the character code for 2
.

- 161,384
- 21
- 275
- 467
-
-
@Highlevelcoder, if you use `numcmp`, like in the book, you'll get results consistent with passing non-numeric characters to `atof`. if you want to treat non-numeric characters some other way, you'll have to define the desired behavior and then implement it. – Rob Kennedy May 17 '11 at 20:41
In the second edition of K&R, section 5.11, the comparison function
int numcmp(char *s1, char *s2); /* defined on page 121 */
is used for numeric sorting (as opposed to using strcmp
for lexicographic sorting). numcmp
calls the function
double atof(char s[]); /* defined on page 71 */
which converts a string to its double-precision floating-point equivalent.
In the example, sorting with the -n
command line argument is done by the double
values returned by the atof
function.

- 6,438
- 3
- 40
- 58