Sams Teach Yourself C in 21 Days

(singke) #1
32: puts(“Enter 0 for reverse order sort, 1 for alphabetical:” );
33: scanf(“%d”, &sort_type);
34:
35: sort(lines, number_of_lines, sort_type);
36: print_strings(lines, number_of_lines);
37: return 0;
38: }
39:
40: int get_lines(char *lines[])
41: {
42: int n = 0;
43: char buffer[80]; /* Temporary storage for each line. */
44:
45: puts(“Enter one line at time; enter a blank when done.”);
46:
47: while (n < MAXLINES && gets(buffer) != 0 && buffer[0] != ‘\0’)
48: {
49: if ((lines[n] = (char *)malloc(strlen(buffer)+1)) == NULL)
50: return -1;
51: strcpy( lines[n++], buffer );
52: }
53: return n;
54:
55: } /* End of get_lines() */
56:
57: void sort(char *p[], int n, int sort_type)
58: {
59: int a, b;
60: char *x;
61:
62: /* The pointer to function. */
63:
64: int (*compare)(char *s1, char *s2);
65:
66: /* Initialize the pointer to point to the proper comparison */
67: /* function depending on the argument sort_type. */
68:
69: compare = (sort_type)? reverse : alpha;
70:
71: for (a = 1; a < n; a++)
72: {
73: for (b = 0; b < n-1; b++)
74: {
75: if (compare(p[b], p[b+1]) > 0)
76: {
77: x = p[b];
78: p[b] = p[b+1];
79: p[b+1] = x;
80: }

414 Day 15

LISTING15.11 continued

25 448201x-CH15 8/13/02 11:13 AM Page 414

Free download pdf