summaryrefslogtreecommitdiff
path: root/reference/C/CONTRIB/OR_USING_C/14.2.c
blob: 07418aaa7a1330c8916cf7ade9b3ec598f161612 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
#include <stdio.h>

#define NSTRS      10         /* number of strings     */
#define STRLEN     16         /* length of each string */

char strs[NSTRS][STRLEN];     /* array of strings      */

main()
{
    int i;
    extern int compare1(), compare2();

    /*
     * Prompt the user for NSTRS strings.
     */
    for (i = 0; i < NSTRS; i++) {
        printf("Enter string #%d: ", i);
        gets(strs[i]);
    }

    /*
     * Sort the strings into ascending order.  There
     * are NSTRS array elements, each one is STRLEN
     * characters long.  Note we give the size of
     * the array element, not the length of the
     * string in it.
     */
    qsort(strs, NSTRS, STRLEN, compare1);

    /*
     * Print the strings.
     */
    printf("\nSorted in ascending order:\n");

    for (i = 0; i < NSTRS; i++)
        printf("\t%s\n", strs[i]);

    /*
     * Now sort the strings in descending order.
     */
    qsort(strs, NSTRS, STRLEN, compare2);

    printf("\nSorted in descending order:\n");

    for (i = 0; i < NSTRS; i++)
        printf("\t%s\n", strs[i]);

    exit(0);
}

/*
 * compare1--compare a and b, and return less than,
 *            greater than, or equal to zero.  Since
 *            we are comparing character strings, we
 *            can just use strcmp to do the work for us.
 */
compare1(a, b)
char *a, *b;
{
    return(strcmp(a, b));
}

/*
 * compare2--this compares a and b, but is used for
 *            sorting in the opposite order.  Thus it
 *            returns the opposite of strcmp.  We can
 *            simulate this by simply reversing the
 *            arguments when we call strcmp.
 */
compare2(a, b)
char *a, *b;
{
    return(strcmp(b, a));
}