Solution for Exercise 19-21

ex1921

#include <stdio.h>
#include <string.h>

int main()
{
    char *fruit[] = {
        "apricot",
        "banana",
        "pineapple",
        "apple",
        "persimmon",
        "pear",
        "blueberry"
    };
    char *temp;
    int a,b,x;

    for(a=0;a<6;a++)
        for(b=a+1;b<7;b++)
            if(strcmp(*(fruit+a),*(fruit+b)) > 0 )
            {
                temp = *(fruit+a);
                *(fruit+a) = *(fruit+b);
                *(fruit+b) = temp;
            }

    for(x=0;x<7;x++)
        puts(fruit[x]);

    return(0);
}

Output

apple
apricot
banana
blueberry
pear
persimmon
pineapple

Notes

* To use the strcmp() function you must include the string.h header file, shown at Line 2.

* The string comparison is done at Line 20. If the value returned by strcmp() is greater than 0, the first string is higher in the alphabet than the second string, and they should be swapped. (To reverse-sort, change the > 0 to < 0.)

* After the determination is made to swap the strings, their addresses are exchanged in Lines 22 through 24, similar to the way bubble sorts have been done elsewhere in the book. You don't need to individually swap the strings' characters, only their addresses. This benefit is one of the beauties of using pointers.