Operator overloading and templates 3.2

2. Write a bubble sort function template that can sort different types of data
#include<iostream>
using namespace std;
template<typename T>
void bubblesort(T array[],int length)
{
    T temp;
    int i,j;
    for(i = 1; i < length ; i++)
    {
        for(j = 0; j < length - i ; j++)
        {
            if(array[j] > array[j+1])
            {
                temp = array[j];
                array[j] = array[j+1];
                array[j+1] = temp;
            }
        }
    }
}

intmain()
{
    int n,i;
    cout << "Please enter the number you want to compare (int type):" << endl;
    cin >> n ;
    double a[n];
    for(i=0;i<n;i++)
    {
        cin >> a[i];
    }
    bubblesort(a,n);
    for(i=0;i<n;i++)
    {
        cout << a[i] <<" ";
    }
    cout << endl;

    cout << "Please enter the number you want to compare (double type):" << endl;
    cin >> n ;
    double b[n];
    for(i=0;i<n;i++)
    {
        cin >> b[i];
    }
    bubblesort(b,n);
    for(i=0;i<n;i++)
    {
        cout << b[i] <<" ";
    }
    cout <<endl;

    cout << "Please enter the number you want to compare (char type):" << endl;
    cin >> n ;
    char c[n];
    for(i=0;i<n;i++)
    {
        cin >> c[i];
    }
    bubblesort(c,n);
    for(i=0;i<n;i++)
    {
        cout << c[i] <<" ";
    }
}


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324691990&siteId=291194637