template function for bubble sort : Function Template « Function « C++






template function for bubble sort

  
#include <iostream>
using namespace std;
template <class X> void bubble_sort(X *items, int size);
template <class X> void show_items(X *items, int size);

int main(void)
{
   int iarray[7] =      {7, 5, 4, 3, 9, 8, 6};
   double darray[5] =   {4.2, 2.5, -0.9, 1.2, 3.0};

   cout << "Here is unsorted integer array: " << endl;
   show_items(iarray, 7);
   cout << "Here is unsorted double array: " << endl;
   show_items(darray, 5);
   bubble_sort(iarray, 7);
   bubble_sort(darray, 5);
   cout << "Here is sorted integer array: " << endl;
   show_items(iarray, 7);
   cout << "Here is sorted double array: " << endl;
   show_items(darray, 5);
}

template <class X> void bubble_sort(X *items, int size)
{
   register int i, j;
   X temp;

   for (i = 1; i < size; i++)
    for (j = size-1; j >= i; j--)
      if (items[j-1] > items[j])
        {
          temp = items[j-1];
          items[j-1] = items[j];
          items[j] = temp;
        }
}

template <class X> void show_items(X *items, int size)
{
   int i;

   for(i=0; i < size; i++)
      cout << items[i] << ", ";
   cout << endl;
}
  
    
  








Related examples in the same category

1.A generic mode finding function.A generic mode finding function.
2.Function template: swap valuesFunction template: swap values
3.Simple template function to accept two parametersSimple template function to accept two parameters
4.template function for find a valuetemplate function for find a value
5.Creating a custom algorithm based on templateCreating a custom algorithm based on template
6.find all template function
7.Using a Binary Function to Multiply Two Ranges
8.Making a Sequence of Random Numbers
9.write function object
10.Use a Function Object to Hold state
11.template function for compacting the items
12.Template copy array function
13.function template for getting the max value
14.Overriding a template function.
15.Using Standard Parameters with Template Functions