Write a function sort3(int& a, int& b, int& c) that swaps its three arguments toarrange them in sorted order. For example,int v = 3;int w = 4;int x = 1;sort3(v, w, x)
Question
Write a function sort3(int& a, int& b, int& c) that swaps its three arguments toarrange them in sorted order. For example,int v = 3;int w = 4;int x = 1;sort3(v, w, x)
Solution
Sure, here is a simple implementation of the function in C++:
void sort3(int& a, int& b, int& c) {
if (a > b)
std::swap(a, b);
if (a > c)
std::swap(a, c);
if (b > c)
std::swap(b, c);
}
This function works by comparing and swapping the values of the variables until they are in sorted order. Here's how it works:
- If
ais greater thanb, swapaandb. - If
ais greater thanc, swapaandc. At this point,ais the smallest of the three numbers. - If
bis greater thanc, swapbandc. Now,bis the second smallest number andcis the largest.
So, if you call sort3(v, w, x) with v = 3, w = 4, and x = 1, the function will rearrange the values of v, w, and x to be 1, 3, and 4, respectively.
Similar Questions
Write a function sort3(int& a, int& b, int& c) that swaps its three arguments toarrange them in sorted order. For example,int v = 3;int w = 4;int x = 1;sort3(v, w, x)
Write a function void sort2(int& a, int& b) that swaps the values of a and b if a isgreater than b and otherwise leaves a and b unchanged. For example,int u = 2;int v = 3;int w = 4;int x = 1;sort2(u, v); // u is still 2, v is still 3sort2(w, x); // w is now 1, x is now 4
C program to sort an array in ascending order
Write a program to sort integers in ascending order. Input is passed in TCL file argument.
Given 3 integer values, arrange those 3 values in ascending order using macrosInput Format:Accept three integer values as a inputOutput Format:Print the output as "min < mid < max
Upgrade your grade with Knowee
Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.