Solution for Exercise 19-22

ex1922

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

int main()
{
    char *fruit[] = {
        "watermelon",
        "banana",
        "pear",
        "apple",
        "coconut",
        "grape",
        "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);
}

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, then 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. There is no need to individually swap the strings' characters, only their addresses. That's one of the beauties of using pointers.