English Deutsch Français Italiano Español Português 繁體中文 Bahasa Indonesia Tiếng Việt ภาษาไทย
All categories

I have a question in an assignment that's really messing with my head...it goes:

2. [Marks: 25] Write a procedure void sort2(int& a, int& b) that swaps the values of
a and b if a is greater 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 3 */
sort2(w, x); /* w is now 1, x is now 4 */
Also write a procedure sort3(int& a, int& b, int& c) that swaps its three inputs to
arrange them in sorted order that uses sort2. For example,
int v = 3;
int w = 4;
int x = 1;
sort3(v, w, x); /* v is now 1, w is now 3, x is now 4 */


any ideas for 10 points??

2007-02-10 14:48:23 · 2 answers · asked by Anonymous in Computers & Internet Programming & Design

2 answers

Similar to "so far north" answer, but...

void swap2(int& a, int& b)
{
if (a > b) { // ONLY swap if a > b
int tmp = a;
a = b;
b = tmp;
}
}

void swap3 (int& a, int& b, int& c)
{
swap2 (a, b) // a become smaller of the 2
swap2 (b, c) // b becomes smaller of the 2
}

2007-02-10 15:37:53 · answer #1 · answered by Alan 6 · 0 0

How about this:

void swap(int& a, int& b)
{
int tmp = a;
a = b;
b = tmp;
}

int _tmain(int argc, _TCHAR* argv[])
{
int a = 1;
int b = 2;
swap(a,b);
.....
}

You can expand on it for the 3-parameter version.

2007-02-10 15:20:21 · answer #2 · answered by so far north 3 · 0 0

fedest.com, questions and answers