/*

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 */

/*

Input :

7

59

72

41

16

27

17

11

Output :

C92.C -> Bubble sort program

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

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= 42

Number of exchanges= 18

*/