/*
Improved version of the 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 bsort2(list, n) /* bsort2 subroutine declaration */
short *list;
short n;
{
short last, k, i, kk;
printf("Sorting\n");
ncomp = 0;
nswap = 0;
last = n - 1;
do {
k = 0;
for (i = 1; i <= last; i++)
{
ncomp++;
if (list[i - 1] > list[i])
{
swap(&list[i - 1], &list[i]); /* Call of swap function */
nswap++;
k = i;
}
} /* End of for{} loop */
for (kk = 0; kk < n; kk++) printf("%5d", list[kk]);
putchar('\n');
last = k;
} while (k != 0);
} /* End of bsort2 subroutine */
main()
{
/* Declaration Statement */
short FORLIM;
clrscr();
printf("C93.C -> Improved
version of the bubble sort\n");
/* Assignment Statements */
printf("Enter the number of Elements : ");
scanf("%hd", &n);
FORLIM = n;
for (i = 1; i <= FORLIM; i++)
{
printf("Element %d : ",i); /* Read element from keyboard entry */
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 */
bsort2(list, n); /* Call of subroutine
*/
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 C93 */
/*
Input :
7
59
72
41
16
27
17
11
Output :
C93.C -> Improved version of the bubble sort
Enter the number of Elements : 7
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
59 41 16 27 17 11 72
41 16 27 17 11 59 72
16 27 17 11 41 59 72
16 17 11 27 41 59 72
16 11 17 27 41 59 72
11 16 17 27 41 59 72
11 16 17 27 41 59 72
After Sorting
11 16 17 27 41 59 72
Number of comparisons= 27
Number of exchanges= 18
*/