C++ PROGRAM Write a template function called MoveToTheBack() which takes as argu
ID: 3675300 • Letter: C
Question
C++ PROGRAM
Write a template function called MoveToTheBack() which takes as arguments an
array and its size (number of cells).
The function moves the largest value of the
array to the end of the array.
The way to do this is to take a pair of cells, and if cell k
is larger than cell k+1, switch them around.
Some other values may get moved around the array.
The function also returns the number of "pair switches" made.
In main declare three arrays with the given values in the order shown:
integer array with values: 3, 5, -1, 4, 2
float array with values 2.1, 0, 3.5, 2, 2 and 1
character array with values "fabs"
Include a template Display function which displays each array when called, with a
space between each value
Here is sample output
3 moves for ints
3 -1 4 2 5
4 moves for float
0 2.1 2 2 1 3.5
2 moves for chars
a b f s
C++ PROGRAM
Write a template function called MoveToTheBack() which takes as arguments an
Explanation / Answer
#include <iostream>
#include <string>
using namespace std;
template <typename T> inline void display (T a[], int n)
{
int i,j;
for(i=0;i<n;i++)
{
cout << a[i]<<" ";
}
cout << endl;
}
template <typename T> inline int MoveToTheBack (T a[], int n)
{
int i,j;
int c=0;
T t;
for(i=0;i<n-1;i++)
{
if((i+1)!=n)
if(a[i]>a[i+1])
{
t=a[i];
a[i]=a[i+1];
a[i+1]=t;
c++;
}
}
return c;
}
int main ()
{
int count;
int i[5] = {3,5,-1,4,2};
double f[6] ={2.1,0,3.5,2,2,1};
char c[4]={'f','a','b','s'};
count=MoveToTheBack(i,5);
cout << count<<" moves for int ";
display(i,5);
count=MoveToTheBack(f,6);
cout << count<<" moves for float ";
display(f,6);
count=MoveToTheBack(c,4);
cout << count<<" moves for int ";
display(c,4);
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.