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.
#include<iostream> #include<vector> using namespace std; void exchangesl(vector<int>& a){ int minIndex = 0; int maxIndex = 0; for(int i = 0;i<a.size();i++){ if(a[i] < a[minIndex]){ minIndex = i; } if(a[i] > a[maxIndex]){ maxIndex = i; } } int t = a[minIndex]; a[minIndex] = a[maxIndex]; a[maxIndex] = t; } int main() { vector<int> v; v.push_back(4); v.push_back(5); v.push_back(1); v.push_back(7); v.push_back(2); exchangesl(v); for(int i = 0;i<v.size();i++){ cout<<v[i]<<endl; } return 0; }
4 5 7 1 2
==============================
void exchangesl(vector<int>& a){ int minIndex = 0; int maxIndex = 0; for(int i = 0;i<a.size();i++){ if(a[i] < a[minIndex]){ minIndex = i; } if(a[i] > a[maxIndex]){ maxIndex = i; } } int t = a[minIndex]; a[minIndex] = a[maxIndex]; a[maxIndex] = t; }