📜  不使用if条件或仅使用max()函数对3个整数进行排序

📅  最后修改于: 2021-04-23 07:07:50             🧑  作者: Mango

给定三个整数,按排序顺序打印它们,而不使用if条件。
例子 :

Input  : a = 3, b = 2, c = 9
Output : 2 3 9

Input  : a = 4, b = 1, c = 9
Output : 1 4 9

方法 :
1.使用max()函数找到a,b,c的最大值。
3.将所有整数乘以–1。再次使用max()函数找到–a,–b,–c的最小值。
4.从上述步骤中将“最大值”和“最小值”相加,然后从(a + b + c)中减去总和。它给了我们中间的元素。
它也适用于负数。

C++
// C++ program to print three numbers
// in sorted order using max function
#include
using namespace std;
 
void printSorted(int a, int b, int c)
{
    // Find maximum element
    int get_max = max(a, max(b, c));
 
    // Find minimum element
    int get_min = -max(-a, max(-b, -c));
 
    int get_mid = (a + b + c)
                 - (get_max + get_min);
 
    cout << get_min << " " << get_mid
        << " " << get_max;
}
 
// Driver code
int main()
{
    int a = 4, b = 1, c = 9;
    printSorted(a, b, c);
    return 0;
}


Java
// Java program to print three numbers
// in sorted order using max function
class GFG
{
     
    static void printSorted(int a, int b, int c)
    {
        // Find maximum element
        int get_max = Math.max(a, Math.max(b, c));
     
        // Find minimum element
        int get_min = -Math.max(-a, Math.max(-b, -c));
     
        int get_mid = (a + b + c)
                      - (get_max + get_min);
     
        System.out.print(get_min + " " + get_mid
                                + " " + get_max);
    }
     
    // Driver code
    public static void main(String[] args)
    {
         
        int a = 4, b = 1, c = 9;
         
        printSorted(a, b, c);
    }
}
 
// This code is contributed by Anant Agarwal.


Python3
# Python3 program to print three numbers
# in sorted order using max function
 
def printSorted(a, b, c):
     
    # Find maximum element
    get_max = max(a, max(b, c))
 
    # Find minimum element
    get_min = -max(-a, max(-b, -c))
 
    get_mid = (a + b + c) - (get_max + get_min)
 
    print(get_min, " " , get_mid, " " , get_max)
 
# Driver Code
a, b, c = 4, 1, 9
printSorted(a, b, c)
 
# This code is contributed by Anant Agarwal.


C#
// C# program to print three numbers
// in sorted order using max function
using System;
 
class GFG {
     
    static void printSorted(int a, int b, int c)
    {
        // Find maximum element
        int get_max = Math.Max(a, Math.Max(b, c));
     
        // Find minimum element
        int get_min = -Math.Max(-a, Math.Max(-b, -c));
     
        int get_mid = (a + b + c) -
                      (get_max + get_min);
     
    Console.Write(get_min + " " + get_mid
                          + " " + get_max);
    }
     
    // Driver code
    public static void Main()
    {
        int a = 4, b = 1, c = 9;
         
        printSorted(a, b, c);
    }
}
 
// This code is contributed by nitin mittal.


PHP


Javascript


输出:

1 4 9