In: Computer Science
1) The provided reorder.cpp file has some code for a function that reorders the values in 3 parameters so that they are in ascending order.
·Start with a function void swap(int &val1, int &val2) that swaps the values of val1 and val2. You will need a local variable to hold the value of one of the parameters to let you do this.
·Write the reorder function called in main(). It should call swap() to exchange values when appropriate.
·Add statements to main() to be able to try out the 3 cases below
Driver to test reorder()
Case 1: values are already in correct order -- leave them alone
1 2 3
Case 2: first > second and first < third
-5 -2 0
Case 3: first > second > third
6 8 10
reorder.cpp
// Reordering values in variables #include <iostream> using namespace std; // swap the values in the two reference integer parameters void swap(int &val1, int &val2) { } // reorder 3 integer values so that // first parameter has smallest value, second parameter has middle value, // third parameter has largest value int main() { int val1 = 1, val2 = 2, val3 = 3; cout << "Driver to test reorder()" << endl; cout << "Case 1: values are already in correct order -- leave them alone" << endl; reorder(val1, val2, val3); cout << val1 << " " << val2 << " " << val3 << endl; return 0; }
// Reordering values in variables #include <iostream> using namespace std; // swap the values in the two reference integer parameters void swap(int &val1, int &val2) { int temp = val1; val1 = val2; val2 = temp; } // reorder 3 integer values so that // first parameter has smallest value, second parameter has middle value, // third parameter has largest value void reorder(int &val1, int &val2, int &val3) { if (val1 >= val2) { swap(val1, val2); } if (val2 >= val3) { swap(val2, val3); } if (val1 >= val2) { swap(val1, val2); } } int main() { int val1 = 1, val2 = 2, val3 = 3; cout << "Driver to test reorder()" << endl; cout << "Case 1: values are already in correct order -- leave them alone" << endl; reorder(val1, val2, val3); cout << val1 << " " << val2 << " " << val3 << endl; val1 = -2; val2 = -5; val3 = 0; cout << "Case 2: first > second and first < third" << endl; reorder(val1, val2, val3); cout << val1 << " " << val2 << " " << val3 << endl; val1 = 10; val2 = 8; val3 = 6; cout << "Case 3: first > second > third" << endl; reorder(val1, val2, val3); cout << val1 << " " << val2 << " " << val3 << endl; return 0; }