/*
  Program C91.C - Interchange sort
*/

#include <stdio.h>

typedef int listarray[1000];   /* Variable Type Declaration */

listarray list;            /* Declaration Statements */
int ncomp, nswap, n, i;

void swap(k, l)    /*  Swap function declaration  */
int *k, *l;
{
  int temp;

  temp = *k;
  *k = *l;
  *l = temp;
  return(0);
} /*  End of swap function  */


void sort1(list, n)      /*  Sort1 function declaration  */
int *list;
int n;
{
  int i, j, k;

  printf("Sorting\n\n");
  ncomp = 0;
  nswap = 0;
  for (i = 0; i <= n - 2; i++)
  {
    for (j = i + 1; j < n; j++)
    {
      ncomp++;
      if (list[i] > list[j])
      {
      swap(&list[i], &list[j]);  /* Call of swap function */
      nswap++;
      }
    } /*  End of inner for{} loop  */
    for (k = 0; k < n; k++) printf("%5d", list[k]);
    putchar('\n');

  } /*  End of outer for{} loop  */
} /*  End of sort1 function  */


main()
{
  int FORLIM;

  printf("C91.C -> demonstration of interchange sort\n");
  printf("Enter number of Elements : ");
  scanf("%d", &n);
  FORLIM = n;

  printf("Enter elements (press ""enter"" between each entry)\n");

  for (i = 1; i <= FORLIM; i++)
  {
    printf("Element %d : ",i);
    scanf("%d", &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  */

  sort1(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 C91  */