Question

What does it mean to numerically sort alpha characters in opposite of lexicographic, like in K&R 5-14 with option -n

Was it helpful?

Solution

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.

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top