CSC 272 - Software II: Principles of Programming Languages

Dr. R. M. Siegfried

A Program in C++ to Sort an array of integers

#include	<iostream>

using	namespace	std;

#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 
	cout << "Before sorting:" << endl;

	for (i = 0;  i < ARRAYLEN;  i++)
		cout << "x[ " << i << "]= " 
			<< array[i] <<  ((i%4 == 3)? '\n': '\t');
	cout << '\n';


	bubble(array, ARRAYLEN);
	cout << "After sorting:" << endl;;
	for (i = 0;  i < ARRAYLEN;  i++)
		cout << "x[ " << i << "]= " 
				<< array[i] <<  ((i%4 == 3)? '\n': '\t');
	cout << '\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 unless there is
an &  in front of the formal parameter's name
void swap(int &a, int &b);

void bubble (int x[], int n)
{
	int hold, j, pass;
	bool	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++ Example List]