Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

1) Write a template function sort in C++ that can be used to sort the elements o

ID: 3548782 • Letter: 1

Question

1) Write a template function sort in C++ that can be used to sort the elements of an array, as long as comparison function > is defined on those elements. Test it in main by sort integer and float array For example, given your template function definition, the code

int a[] = {4,2,1,3};

float b[] = {6.7,3.4,1.2};

cout << sort(a,4) << endl; // the parameters are the array and the size of the array

cout << sort(b,3) << endl; //b is a float array

// use a for loop to print the sorted element as follows

1,2,3,4

1.2,3.4,6.7

Explanation / Answer

#include<iostream>

#include<algorithm>

using namespace std;


void sort_array(float a[], int b){

sort(a,a+b);

for(int i=0;i<b;i++){

cout << a[i] << " ";

}

}


int main(){

int size;

float a[1000];

cout << "Enter the size of the array :";

cin >> size;

float x;

cout << "Enter the elements of the array :" << endl;

for(int i=0; i<size; i++){

cin >> a[i];

}

cout << "The sorted array is : "

sort_array(a, size);

}