/*
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 */
/*
Input :
7
59
72
41
16
27
17
11
Output :
C91.C -> demonstration of interchange sort
Enter number of Elements : 7
Enter elements (press enter between each entry)
Element 1 : 59
Element 2 : 72
Element 3 : 41
Element 4 : 16
Element 5 : 27
Element 6 : 17
Element 7 : 11
Press Enter to continue...
Before Sorting
59 72 41 16 27 17 11
Sorting
11 72 59 41 27 17 16
11 16 72 59 41 27 17
11 16 17 72 59 41 27
11 16 17 27 72 59 41
11 16 17 27 41 72 59
11 16 17 27 41 59 72
After Sorting
11 16 17 27 41 59 72
Number of comparisons= 21
Number of exchanges= 18
*/