Solution for Exercise 12-16

ex1216

#include <stdio.h>

int main()
{
    const int size = 21;
    char bubble[] = "C Programming is fun!";
    char temp;
    int inner,outer,x;

    /* Display original array */
    puts("Original Array:");
    for(x=0;x<size;x++)
        printf("%c",bubble[x]);
    putchar('\n');

    /* Bubble sort */
    for(outer=0;outer<size-1;outer++)
    {
        for(inner=outer+1;inner<size;inner++)
        {
            if(bubble[outer] > bubble[inner])
            {
                temp=bubble[outer];
                bubble[outer] = bubble[inner];
                bubble[inner] = temp;
            }
        }
    }

    /* Display sorted array */
    puts("Sorted Array:");
    for(x=0;x<size;x++)
        printf("%c",bubble[x]);
    putchar('\n');

    return(0);
}

Output

Original Array:
C Programming is fun!
Sorted Array:
   !CPafggiimmnnorrsu

Notes

* Sorting works the same, no matter the array's variable type.

* ASCII code values for upper case letters are smaller than those for lower case letters, so the capitals before lower case letters in the sort. Spaces have the lowest ASCII value of any displayable character, so the string's three spaces appear first in the output.

* Setting the string's length as a constant value solves a lot of problems, but still it's not cool to count the characters in a string to set the value. As an alternative, you could try to code a solution that takes advantage of the null character at the end of the string. Or you can wait until Chapter 13 when you're introduced to the strlen() function.