/** * sort.c - A sort utility, based on code from K&R. */ // +---------+-------------------------------------------------------- // | Headers | // +---------+ #include #include #include #include "readlines.h" #include "writelines.h" #include "qsort.h" #include "swap.h" // +-----------+------------------------------------------------------ // | Constants | // +-----------+ #define MAXLINES 5000 /* max #lines to be sorted */ // +---------+-------------------------------------------------------- // | Globals | // +---------+ char *lineptr[MAXLINES]; /* pointers to text lines */ // +--------------------------+--------------------------------------- // | Function Predeclarations | // +--------------------------+ int numcmp(const char *, const char *); // +------+----------------------------------------------------------- // | Main | // +------+ /* sort input lines */ int main (int argc, char *argv[]) { int nlines; /* number of input lines read */ int (*comparator)(const char *, const char *); comparator = strcmp; if ((argc > 1) && (strcmp(argv[1], "-n") == 0)) comparator = numcmp; if ((nlines = readlines(lineptr, MAXLINES)) >= 0) { kr_qsort ((char**) lineptr, 0, nlines-1, comparator); writelines(lineptr, nlines); return 0; } else { printf("input too big to sort\n"); return 1; } } // main // +-----------------------+------------------------------------------ // | Function Declarations | // +-----------------------+ int numcmp (const char *s1, const char *s2) { double v1, v2; v1 = atof (s1); v2 = atof (s2); if (v1 < v2) { #ifdef DEBUG printf ("%lf (%s) < %lf (%s)\n", v1, s1, v2, s2); #endif return -1; } else if (v1 > v2) { #ifdef DEBUG printf ("%lf (%s) > %lf (%s)\n", v1, s1, v2, s2); #endif return 1; } else { #ifdef DEBUG printf ("%lf (%s) == %lf (%s)\n", v1, s1, v2, s2); #endif return 0; } } // numcmp