/** * Nick's favorite sorting routine. */ // +---------+------------------------------------------------------- // | Headers | // +---------+ #include // strlen, strcmp #include // printf // +-------+--------------------------------------------------------- // | Types | // +-------+ /** * Procedures that compare two strings for order. Like strcmp. */ typedef int (*Comparator)(char *str1, char *str2); // +-----------+----------------------------------------------------- // | Utilities | // +-----------+ /** * Compare to strings by length. */ int scl (char *str1, char *str2) { return strlen (str1) - strlen (str2); } // scl /** * Swap two elements in an array. */ void swap (char *strings[], int k, int l) { char *um = strings[k]; strings[k] = strings[l]; strings[l] = um; } // swap /** * Some strange sorting algorithm that isn't really bubblesort. */ int sort (char *strings[], int len, Comparator compare) { int i, j; for (i = 0; i < len; i++) { for (j = 0; j < len-1; j++) { if (compare (strings[j], strings[j+1]) > 0) { swap (strings, j, j+1); } // if out of order } // for j } // for i return 1; } // sort /** * Print an array of strings to stdout. */ void printstrings (char *strings[], int len) { int i; if (len == 0) { printf ("{}"); return; } printf ("{\"%s\"", strings[0]); for (i = 1; i < len; i++) { printf (", \"%s\"", strings[i]); } // for printf ("}"); } // printstrings // +------+---------------------------------------------------------- // | Main | // +------+ int main (int argc, char *argv[]) { char **strings = argv+1; int len = argc-1; printf ("Original array:\t"); printstrings (strings, len); printf ("\n"); if (!sort (strings, len, scl)) printf ("Sorting failed!\n"); printf ("After sorting by len: \t"); printstrings (strings, len); printf ("\n"); if (!sort (strings, len, (Comparator) strcmp)) printf ("Sorting failed!\n"); printf ("After sorting alphabetically: \t"); printstrings (strings, len); printf ("\n"); return 0; } // main