0

I need to create a decision tree that sorts any three integers in ascending order.
This is what I did:

#include <iostream>
using namespace std;
        
int main()
{
    int x, y, z;
    cout << "Enter three integers: ";
    cin >> x >> y >> z;
    cout << "Your three integers in ascending order are: ";
            
    if(x <= y){
        if(x <= z) cout << x << " ";
        if(y <= z) cout << y << " " << z << endl;
        if(z <= y) cout << z << " " << y << endl;
    }
    else
        if(y <= x){
            if(y <= z) cout << y << " ";
            if(x <= z) cout << x << " " << z << endl;
            if(z <= x) cout << z << " " << x << endl;
        }
    else
        if(z <= x){
            if(z <= y) cout << z << " ";
            if(y <= x) cout << y << " " << x << endl;
            if(x <= y) cout << x << " " << y << endl;
        }
            
}

I don't know what to do to get it to work when the numbers entered are in zyx or zxy order.

3
Contributors
3
Replies
4
Views
10 Years
Discussion Span
Last Post by WaltP
0

You have to swap the values if they are not in ascending order. Something like :

if (x>y)
{ int tmp =x
x=y
y=tmp
}

etc...
It wasn't clear whether the you just wanted to output the numbers in ascending order, or you had to maintain the variable name as well. Seems that don't
so a simple variable swap should be OK
You get the idea...

0

i don't understand what you're saying to do. can you clarify? the variable names do not need to stay the same.

0

All you're trying to do is output the values in order. That's not a sort.

Check if x > y. If so, move x into y and y into x (switch the values).

Then do it again for y and z.

You'll have to go back and retest x and y again.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.