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

Please write these problems in C++ format 8. Write a void function named swap_ha

ID: 3626511 • Letter: P

Question

Please write these problems in C++ format

8. Write a void function named swap_halves that passes in a vector of integers and swaps
the values in the first half of the vector with the values in the second half of the vector.
For example, if the vector argument passed in has values in the order:
4 8 2 9 1 7 6 3
then when the function returns the order of values in the vector argument will be:
1 7 6 3 4 8 2 9
Notice that this is not reversing the order of the values.
If the vector argument passed in has an odd number of values, then do not move the middle
value. For example, if the vector argument passed in has values in the order:
2 9 3 4 6
then when the function returns the order of values in the vector argument will be:
4 6 3 2 9
Notice that the value 3 did not move from the middle.
Pleae also define a useful helper function and use it correctly within your definition of swap_halves.

Explanation / Answer

#include<iostream>
#include<vector>
using namespace std;
void swap_values(vector<int>& v)
{
int k=v.size()/2;
for(int i=0; i<v.size()/2; i++)
{
int temp = v[i];
v[i]=v[k];
v[k]=temp;
k++;
}
}
int main()
{
int a[]={4, 8, 2, 9, 1, 7, 6, 3};
vector<int> v(a,a+sizeof(a)/sizeof(int));
cout << "before swap"<<endl;
for(int i=0; i<v.size(); i++)
cout << v[i]<<" ";
swap_values(v);
cout << " after swap"<<endl;
for(int i=0; i<v.size(); i++)
cout << v[i]<<" ";

return 0;
}