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.

Recommended Answers

All 3 Replies

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...

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

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.