BouncyKnight
BouncyKnight

Reputation: 47

Is there any better way to sort three integers in C++?

In the programming textbook I'm using (Programming: Principles and Practice using C++ by Bjarne Stroustrup), I'm trying to do one of the exercises found in the very early chapters (before the introduction of arrays or anything), but I can only solve it using an algorithm that looks quite weird and "backwards" to me. The exercise is to read from the console 3 integers and to sort them according to size, separated by commas. Here is what I wrote:

#include <iostream>

using namespace std;

int main()
{
    int a, b, c;
    cout << "Enter three integers: ";
    cin >> a >> b >> c;
    if (a <= b and a <= c) {
        cout << a << ", ";
        if (b < c)
            cout << b << ", " << c;
        else
            cout << c << ", " << b;
        return 0;
    }
    if (b <= a and b <= c) {
        cout << b << ", ";
        if (a < c)
            cout << a << ", " << c;
        else
            cout << c << ", " << a;
        return 0;
    }
    if (c <= a and c <= b) {
        cout << c << ", ";
        if (a < b)
            cout << a << ", " << b;
        else
            cout << b << ", " << a;
        return 0;
    }
    return 0;
}

I know it's very long, but I can't think of any other way to do it with the tools at my disposal (if statements). Can you please help me and show me if there is any other way to do it? Thanks!

Upvotes: 0

Views: 179

Answers (3)

nullElement
nullElement

Reputation: 11

Hope this helps:

#include <iostream>

using namespace std;

int main()
{
    int a, b, c, x, mid, max;
    cout << "Enter three integers: ";
    cin >> a >> b >> c;
    if (a<b){
        x = a;
        max = b;

    }
    else {
        x = b;
        max = a;
    }

    if (c < x){
       mid = x;
       x = c;
    }
    if (c > max){
        mid = max;
        max = c;
    }
    else
      mid = c;

    cout << x << ", " << mid <<", "<<max;

  }

Upvotes: 1

Aykhan Hagverdili
Aykhan Hagverdili

Reputation: 29985

Depends on what you mean by "better". There is a shorter way to do that, just like most other things in C++:

#include <iostream>
#include <iterator>
#include <algorithm>
#include <cstdio>

int main() {
    std::istream_iterator<int> it{std::cin};
    int a[]{ *it++, *it++, *it++ };
    std::sort(std::begin(a), std::end(a));
    std::printf("%d, %d, %d\n", a[0], a[1], a[2]);
}

Whether or not shorter is better is another discussion.

Upvotes: 3

molbdnilo
molbdnilo

Reputation: 66431

You can also do this without invoking std::sort, sorting by hand:

// Put the smallest number in a.
if (b < a)
    std::swap(a, b);
if (c < a)
    std::swap(a, c);
// Arrange the other two numbers.
if (c < b)
    std::swap(b, c);
std::cout << a << ", " << b << ", " << c << '\n';

Upvotes: 2

Related Questions