/*

Cocktail shaker 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;

return(0);

} /* End of swap function */

void bsortr(list, l, m, k) /* bsortr subroutine declaration */

short *list;

short *l, *m, *k;

{

/* Right bubble sort */

short i, FORLIM;

(*m)--;

*k = 0;

FORLIM = *m;

for (i = *l; i <= FORLIM; 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 */

*m = *k;

} /* End of bsortr subroutine */

void bsortl(list, l, m, k) /* bsortl function declaration */

short *list;

short *l, *m, *k;

{

/* Left bubble sort */

short i, FORLIM;

(*l)++;

*k = 0;

FORLIM = *l;

for (i = *m; i >= FORLIM; i--)

{

ncomp++;

if (list[i - 1] < list[i - 2])

{

swap(&list[i - 1], &list[i - 2]); /* Call of swap function */

nswap++;

*k = i;

}

} /* End of for{} loop */

*l = *k;

} /* End of bsortl subroutine */

void shake(list, n) /* Shake subroutine declaration */

short *list;

short n;

{

short left, right, i, k;

ncomp = 0;

nswap = 0;

left = 1;

right = n;

i = 1;

do

{

bsortr(list, &left, &right, &k); /* Call of subroutine */

if (k != 0)

bsortl(list, &left, &right, &k); /* Call of subroutine */

i++;

} while (i <= n && k != 0); /* End of while{} loop */

} /* End of Shake subroutine */

main()

{

/* Declaration Statements */

short FORLIM;

clrscr();

printf("C94.C -> Cocktail Shaker Sort\n");

/* Assignment Statements */

printf("Enter the 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 */

shake(list, n); /* Call of shake 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 C94 */

/*

Input :

7

59

72

41

16

27

17

11

Output :

C94.C -> Cocktail Shaker 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

After Sorting

11 16 17 27 41 59 72

Number of comparisons= 21

Number of exchanges= 18

*/