/*

 * bubble.c

 * This program reads a sequence of intergers, terminated by (-1), and sorts

 * it using the bubble-sort algorithm.

 */

 

#include <stdio.h>

 

#define MAX_SIZE 100

 

/* Prototypes: */

void bubble_sort (int *arr, int n);

 

int main ()

{

  const int stop_code = -1;

  int       array[MAX_SIZE];

  int       n_numbers = 0;

  int       curr;

  int       i;

 

  /* Read the input numbers. */

  while (n_numbers < MAX_SIZE)

  {

    /* Read the next number. */

    printf ("Please enter the next number (or -1 to stop): ");

    scanf ("%d", &curr);

 

    if (curr == stop_code)

      break;

 

    /* Store it. */

    array[n_numbers] = curr;

    n_numbers++;

  }

 

  /* Sort the numbers and print them. */

  bubble_sort (array, n_numbers);

 

  for (i = 0; i < n_numbers; i++)

    printf ("%d ", array[i]);

  printf ("\n");

 

  return (0);

}

 

/* ------------------------------------------------------------------------

 * Function: bubble_sort

 * Purpose : Sort an array of integers in an ascending order, using the

 *           bubble-sort algorithm.

 * Input   : n   - The number of intergers in the array.

 * In/Out  : arr - The array.

 * Returns : Nothing.

 */

void bubble_sort (int *arr, int n)

{

  int     i, j;

  int     temp;

 

  /* Let i run over all entries (except the last). */

  for (i = 0; i < n - 1; i++)

  {

    /* Let j run over all entries from (i+1) until the last. */

    for (j = i + 1; j < n; j++)

    {

      /* If arr[i] > arr[j], swap the two entries. */

      if (arr[i] > arr[j])

      {

        temp = arr[i];

        arr[i] = arr[j];

        arr[j] = temp;

      }

    }

  }

 

  return;

}