Minimum and maximum#2606

Minimum and maximum (Editorial)

Compare two numbers and first print the smaller one, followed by the larger one.

The second solution involves checking if a > b. If true, swap their values using a third variable. Then, print the numbers and .

Algorithm implementation

Read the input data.

scanf("%d %d",&a,&b);

Compare and print the numbers in the required order.

if (a < b) 
  printf("%d %d\n",a,b);
else
  printf("%d %d\n",b,a);

Algorithm implementation — swap

Read the input data.

scanf("%d %d",&a,&b);

If a > b, swap the values of and .

if (a > b) 
{
  temp = a; a = b; b = temp;
}

Print the values and , where a \le b.

printf("%d %d\n",a,b);

Algorithm implementation — ternary operator

Read the input data.

scanf("%d %d",&a,&b);

Compute the minimum and maximum values between the two numbers and .

min = (a < b) ? a : b;
max = (a > b) ? a : b;

Print the minimum and maximum of the two numbers and .

printf("%d %d\n",min,max);

Algorithm implementation — using the functions

#include <stdio.h>

int a, b;

int min(int a, int b)
{
  return (a < b) ? a : b;
}

int max(int a, int b)
{
  return (a > b) ? a : b;
}

int main(void)
{
  scanf("%d %d",&a,&b);
  printf("%d %d\n",min(a,b),max(a,b));
  return 0;
}

Java implementation

import java.util.*;

public class Main
{
  public static void main(String[] args)
  {
    Scanner con = new Scanner(System.in);
    int a = con.nextInt();
    int b = con.nextInt();
    
    System.out.println(Math.min(a,b) + " " + Math.max(a,b));
    con.close();
  }
}   

Python implementation

Read the input data.

a, b = map(int, input().split())

If a > b, swap the values of and .

if a > b:
  a, b = b, a

Print the values and , where a \le b.

print(a, b)

C# implementation

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleAppCSharp
{
  class Program
  {
    static void Main(string[] args)
    {
      string[] values = Console.ReadLine().Split(' ');
      int x = int.Parse(values[0]);
      int y = int.Parse(values[1]);

      int min = (x < y) ? x : y;
      int max = (x > y) ? x : y;
      Console.WriteLine("{0} {1}", min, max);
    }
  }
}