3 integers from greatest to least

后端 未结 1 1815
情歌与酒
情歌与酒 2021-01-29 15:38

I am beginner to C++ and I using \"Programming: Principles and Practice Using C++ (Second Edition). The question asked: \"Write a program that prompts the user to enter three in

相关标签:
1条回答
  • 2021-01-29 16:41

    std::sort (as suggested by Richard) is one solution, though IMHO such heavy gun isn't necessary for a data set of 3 elements. For 3 variables, the sorting can be unrolled (as the OP tried) and the various available sorting algorithms probably differ that much (concerning the order of comparisons and swaps) or won't bring any improvement concerning this little sample.

    Thus, I made an unrolled sort (re-sembling what I believe would be bubble sort):

    #include <iostream>
    
    void sort(int &a, int &b, int &c)
    {
      if (a < b) std::swap(a, b);
      if (b < c) std::swap(b, c);
      if (a < b) std::swap(a, b);
    }
    
    int main()
    {
      // any permutation of { 1, 2, 3 } (i.e. any possible order)
      int tests[][3] = {
        { 1, 2, 3 },
        { 1, 3, 2 },
        { 2, 1, 3 },
        { 2, 3, 1 },
        { 3, 1, 2 },
        { 3, 2, 1 }
      };
      // apply sort() to every test set
      for (int *test : tests) {
        int a = test[0], b = test[1], c = test[2];
        std::cout << "a: " << a << " b: " << b << " c: " << c << " sorted: ";
        sort(a, b, c);
        std::cout << "a: " << a << " b: " << b << " c: " << c << '\n';
      }
      // done
      return 0;
    }
    

    Output:

    a: 1 b: 2 c: 3 sorted: a: 3 b: 2 c: 1
    a: 1 b: 3 c: 2 sorted: a: 3 b: 2 c: 1
    a: 2 b: 1 c: 3 sorted: a: 3 b: 2 c: 1
    a: 2 b: 3 c: 1 sorted: a: 3 b: 2 c: 1
    a: 3 b: 1 c: 2 sorted: a: 3 b: 2 c: 1
    a: 3 b: 2 c: 1 sorted: a: 3 b: 2 c: 1
    

    Live Demo on coliru

    0 讨论(0)
提交回复
热议问题