In: Computer Science
In C++, create a function exchangesl that takes an argument of an array of integers ( for C++ use implement void exchangesl(vector<int>& a) . Those integers need to be changed so that the smallest and largest values in the array are exchanged. Assume that there is at least one element, if the largest value occurs more than once then exchange the first instance, if the smallest value happens more than once then exchange the last instance.
Use the following file:
Tester.cpp
#include <vector> #include <iostream> using namespace std; void exchangesl(vector<int>&); void print(vector<int> v) { for (int i = 0; i < v.size(); i++) { if (i == 0) cout << "["; else cout << ", "; cout << v[i]; } cout << "]" << endl; } main() { vector<int> a = { 1, 9, -1, 4, -1, 6, 11, 8 }; exchangesl(a); print(a); cout << "Expected: [1, 9, -1, 4, 11, 6, -1, 8]" << endl; vector<int> b = { 1, 9, -1, 4, -1, 6, 11, 8, 9, -1 }; exchangesl(b); print(b); cout << "Expected: [1, 9, -1, 4, -1, 6, -1, 8, 9, 11]" << endl; vector<int> c = { 1, 2, 3, 4, 5, 4, 3, 2, 1, 2, 3, 4, 5, 4, 3, 2, 1 }; exchangesl(c); print(c); cout << "Expected: [1, 2, 3, 4, 1, 4, 3, 2, 1, 2, 3, 4, 5, 4, 3, 2, 5]" << endl; }
Given below is completed code with output. Please do rate the
answer if it helped. Thank you.
#include <vector>
#include <iostream>
using namespace std;
void exchangesl(vector<int>& v);
void print(vector<int> v)
{
for (int i = 0; i < v.size(); i++)
{
if (i == 0) cout << "["; else cout << ", ";
cout << v[i];
}
cout << "]" << endl;
}
main()
{
vector<int> a = { 1, 9, -1, 4, -1, 6, 11, 8 };
exchangesl(a);
print(a);
cout << "Expected: [1, 9, -1, 4, 11, 6, -1, 8]" <<
endl;
vector<int> b = { 1, 9, -1, 4, -1, 6, 11, 8, 9, -1
};
exchangesl(b);
print(b);
cout << "Expected: [1, 9, -1, 4, -1, 6, -1, 8, 9, 11]"
<< endl;
vector<int> c = { 1, 2, 3, 4, 5, 4, 3, 2, 1, 2, 3, 4, 5, 4,
3, 2, 1 };
exchangesl(c);
print(c);
cout << "Expected: [1, 2, 3, 4, 1, 4, 3, 2, 1, 2, 3, 4, 5, 4,
3, 2, 5]" << endl;
}
void exchangesl(vector<int>& v){
int smallIdx = 0, bigIdx = 0;
for(int i = 1; i < v.size(); i++){
if(v[i] <= v[smallIdx])
smallIdx = i;
else if(v[i] > v[bigIdx])
bigIdx = i;
}
if(smallIdx != bigIdx){
//swap
int temp = v[smallIdx];
v[smallIdx] = v[bigIdx];
v[bigIdx] = temp;
}
}
output
------
[1, 9, -1, 4, 11, 6, -1, 8]
Expected: [1, 9, -1, 4, 11, 6, -1, 8]
[1, 9, -1, 4, -1, 6, -1, 8, 9, 11]
Expected: [1, 9, -1, 4, -1, 6, -1, 8, 9, 11]
[1, 2, 3, 4, 1, 4, 3, 2, 1, 2, 3, 4, 5, 4, 3, 2, 5]
Expected: [1, 2, 3, 4, 1, 4, 3, 2, 1, 2, 3, 4, 5, 4, 3, 2,
5]