Programming and Graphics

(Kiana) #1

4.10 Function templates 123


Bubble sort


The header filebsort.hcontaining the implementation of the bubble-sort
algorithm discussed in Section 3.8 reads:


#ifndef BSORTH
#define BSORTH

using namespace std;

template <class T>
T bsort (int n, T x[])
{
int Istop,k,i;
T save;
k = n-1; // number of comparisons
do{
Istop = 1; // will stop if Iflag 1
for (i=1;i<=k;i++) // compare
{
if(x[i]>x[i+1])
{save = x[i]; // swap
x[i]=x[i+1];
x[i+1] = save;
Istop = 0; // an exchange occurred; do not stop
}
}
k--; // reduce the number of comparisons
}while(Istop==0);

return x[n];
}

#endif

This function template returns to the calling program the entry at the bottom
of the sorted list. The function has two arguments: the integern, and the vector
variablex[]whose data type is left unspecified.


ReplacingTwith an actual data type, such asfloat, we obtain the
familiar function definition:


float bsort (int n, float x[])

The main programcities.cclisted below calls this template function to
alphabetize a list of cities:


#include <iostream>
#include <iomanip>
Free download pdf