Templates

Here we have written a Template bubble sort. This is an inefficient sort to start with, and here we have not even optimized it to stop sorting when there are no swaps in a single pass. However, I wanted to keep it as simple as possible to illustrate using the Temple to write a function with arrays.

Note that arrays are ALWAYS passed by reference and we do not need the &. However, we do need to pass the size of the array as an argument.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
//Use template to sort and print an array
#include<iostream>
#include<string>
using namespace std;
template <class T>
void show(T a[],int count) {
   for(int i=0;i<count;i++) {
      cout<<a[i];
      if(i<count-1) cout<<", "; //only print comma if not last
   }//for loop
   cout<<endl;
} //show
template <class T>
void bubbleSort(T a[],int count) {
   //A very inefficient bubble sort
   for(int i=0;i<count;i++) {
      for(int j=0;j<count-1;j++) {
         if(a[j]>a[j+1]) swap(a[j],a[j+1]);
      } //j inner loop
   }//i outer loop
} //show

int main() {
   int num[]={20,5,3,17,2};
   int count=sizeof(num)/sizeof(int);
   cout<<"There are "<<count<<" integers\n";
   bubbleSort(num,count);
   show(num,count);
   double d[]={5.5,-20, 0.25,6.1};
   count=sizeof(d)/sizeof(double);
   cout<<"There are "<<count<<" doubles\n";
   bubbleSort(d,count);
   show(d,count);
   string name[]={"Mary", "Bill","Amy","Jay","Mike","Alex"};
   count=sizeof(name)/sizeof(string);
   cout<<"There are "<<count<<" names\n";
   bubbleSort(name,count);
   show(name,count);
   system("pause");
   return 0;
}//main
CODE
There are 5 integers
2, 3, 5, 17, 20
There are 4 doubles
-20, 0.25, 5.5, 6.1
There are 6 names
Alex, Amy, Bill, Jay, Mary, Mike
Press any key to continue . . .

NEXT: A Template bubble sort with function prototype