Solution for Exercise 12-14

ex1214

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main()
{
    const int size = 40;
    int bubble[size];
    int inner,outer,temp,x;

    srand((unsigned)time(NULL));
    /* Display original array */
    puts("Original Array:");
    for(x=0;x<size;x++)
    {
        /* keep the value between 1 and 100 */
        bubble[x] = rand() % 100 + 1;
        printf("%d\t",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("%d\t",bubble[x]);
    putchar('\n');

    return(0);
}

Output

Original Array:
29 83 76 88 90 52 92 18 65 58 66 13 24 71 12 93 15 33 8 97 17 88 5 65 4 19 38 56 47 86 47 22 79 39 95 1 79 90 59 3
Sorted Array:
1 3 4 5 8 12 13 15 17 18 19 22 24 29 33 38 39 47 47 52 56 58 59 65 65 66 71 76 79 79 83 86 88 88 90 90 92 93 95 97

Notes

* Of course, the values you see in your program's output will be different.

* The stdlib.h and time.h header files are required (Lines 2 and 3) for the rand(), srand(), and time() functions.

* Line 11 seeds the randomizer, as is discussed in Chapter 11.

* Line 17 assigns the random values to the array. The random value is clipped by the modulus operator so that it falls into the range 1 to 100.

* All solutions are valid as long as the results are what you intended.