Write a program which has a function template for sorting an array of given data types
#include <iostream>
#include <algorithm>
using namespace std;
template<typename T>
void Sort(T array[], int size){
for (int i = 0; i < size - 1; i++)
for (int j = size - 1; i < j; j--)
if (array[j] < array[j - 1])
swap(array[j], array[j - 1]);
}
int main(){
int x[7] = {1, 2, 5, 7, 8, 0, 5};
char c[7] = {'a', 'b', 'z', 'f', 'c', 'g', 'e'};
cout<<"Unsorted: \n";
for(int i = 0; i < 7; i++) cout<<x[i]<<" ";
cout<<endl;
for(int i = 0; i < 7; i++) cout<<c[i]<<" ";
cout<<endl<<endl;
Sort<int>(x, 7);
Sort<char>(c, 7);
cout<<"Sorted: \n";
for(int i = 0; i < 7; i++) cout<<x[i]<<" ";
cout<<endl;
for(int i = 0; i < 7; i++) cout<<c[i]<<" ";
cout<<endl;
return 0;
}
Comments
Leave a comment