CSC 272 - Software II: Principles of Programming Languages

Dr. R. M. Siegfried

A Program in C to Sort an array of integers

#include	<stdio.h>

/* True is any non-zero value - logical operations return 1 */
#define		TRUE 	1
/* False is always zero */
#define		FALSE	0       

#define	ARRAYLEN	8
/* Initializing an external array */
int	array[ARRAYLEN] = {25, 57, 48, 37, 12, 92, 86, 33};

/* Prototype for a bubble sort - Arrays are passed by reference */
void bubble (int x[], int n);

int	main(void)
{
	int	i;
	extern int	array[];

	/* Print a string */
	puts("Before sorting:");
	/* %d - print an integer in decimal form
		%c - print a character
		i%4 == 3? '\n: '\t' means that if the remainder of i/4 is 3
			print a newline otherwise print a tab*/  
	for (i = 0;  i < ARRAYLEN;  i++)
		printf("x[%d] = %d%c", i, array[i], i%4 == 3? '\n': '\t');
	putchar('\n');


	bubble(array, ARRAYLEN);
	puts("After sorting:");
	for (i = 0;  i < ARRAYLEN;  i++)
		printf("x[%d] = %d%c", i, array[i], i%4 == 3? '\n': '\t');
	putchar('\n');

	return(0);
}

/* Prototypes don't have to be on top as long as they are
			before the function is used*/

/* Scalar variables are passed by value*/
void swap(int *a, int *b);

void bubble (int x[], int n)
{
	int hold, j, pass;
	int	switched = TRUE;

	for (pass = 0;  pass < n - 1 && switched;  pass++)	{
		/* outer loop controls the number of passes */
		/* Initially nothing is switched */
		switched = FALSE;
		for (j = 0;  j < n-pass-1;  j++)
			/* Inner loop governs each individual pass */
			if (x[j] > x[j+1])	{
				/* Elements out of order  */
				switched = TRUE;
				/* Pass their addresses so that they
                                	change is passed back */
				swap(&x[j], &x[j+1]);
			} 	
        }
}

/*  Passing by reference in C requires working with pointers */ 
void swap(int *a, int *b)
{
	int	temp;

	temp = *a;
	*a = *b;
	*b = temp;
}

[Back to the C Program Index]