Answer to Question #188739 in C++ for Shreetej Dilip Phu

Question #188739

Write a program which has a function template for sorting an array of given data types


1
Expert's answer
2021-05-03T17:06:11-0400
#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;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
APPROVED BY CLIENTS