/*
  C92.C -> Example of Bubble Sort.
*/

#include <stdio.h>

typedef short listarray[1000];  /* Variable type declaration */

listarray list;            /* Global Variable declaration */
short ncomp, nswap, n, i;

void swap(k, l)    /* Swap function declaration */
short *k, *l;
{
  short temp;

  temp = *k;
  *k = *l;
  *l = temp;
} /*  End of swap function  */


void bsort1(list, n)    /* bsort1 subroutine declaration */
short *list;
short n;
{
  short i, k, kk;

  printf("Sorting\n\n");
  ncomp = 0;
  nswap = 0;
  do
  {
    k = 0;
    for (i = 1; i < n; i++)
    {
      ncomp++;
      if (list[i - 1] > list[i])
      {
      swap(&list[i - 1], &list[i]);   /*  Call of swap function  */
      nswap++;
      k = 1;
      }
    } /*  End of for{} loop  */

    for (kk = 0; kk < n; kk++) printf("%5d", list[kk]);
    putchar('\n');

  } while (k != 0);     /* End of while{} loop */
} /*  End of bsort1 subroutine  */


main()
{
  /*  Declaration Statements  */
  short FORLIM;

  clrscr();   /* Clear screen */
  printf("C92.C -> Bubble sort program\n");

  /*  Assignment Statements  */
  printf("Enter Number of Elements : ");
  scanf("%hd", &n);
  FORLIM = n;

  printf("Enter elements (press ""enter"" between each entry)\n");

  for (i = 1; i <= FORLIM; i++)
  {
    printf("Element %d : ",i);
    scanf("%hd", &list[i - 1]);
  }

  printf("Press ""Enter"" to continue...\n");
  scanf("");
  printf("\n");

  printf("Before Sorting\n\n");
  FORLIM = n;
  for (i = 1; i <= FORLIM; i++) printf("%5d", list[i - 1]);
  printf("\n\n");

  /*  Sort with subroutines  */

  bsort1(list, n);    /*  Call of subroutine  */

  /*  Print results  */

  printf("\nAfter Sorting\n\n");
  FORLIM = n;

  for (i = 1; i <= FORLIM; i++) printf("%5d", list[i - 1]);

  printf("\n\nNumber of comparisons=%3d\n", ncomp);
  printf("Number of exchanges=%3d\n\n\n", nswap);

  return(0);
}
/*  End of main Program C92  */