Среднее из трех с использованием минимума сравнений

Опубликовано: 5 Января, 2022

Учитывая три различных числа a, b и c, найдите число со значением посередине.
Примеры :

 Ввод: a = 20, b = 30, c = 40.
Выход: 30

Ввод: a = 12, n = 32, c = 11
Выход: 12

Рекомендуется: сначала попробуйте свой подход в {IDE}, прежде чем переходить к решению.

Простой подход:

C ++

// CPP program to find middle of three distinct
// numbers
#include <bits/stdc++.h>
using namespace std;
int middleOfThree( int a, int b, int c)
{
// Checking for b
if ((a < b && b < c) || (c < b && b < a))
return b;
// Checking for a
else if ((b < a && a < c) || (c < a && a < b))
return a;
else
return c;
}
// Driver Code
int main()
{
int a = 20, b = 30, c = 40;
cout << middleOfThree(a, b, c);
return 0;
}

Джава

// Java program to find middle of
// three distinct numbers
import java.util.*;
class Middle
{
// Function to find the middle of three number
public static int middleOfThree( int a, int b,
int c)
{
// Checking for b
if ((a < b && b < c) || (c < b && b < a))
return b;
// Checking for a
else if ((b < a && a < c) || (c < a && a < b))
return a;
else
return c;
}
// driver code
public static void main(String[] args)
{
int a = 20 , b = 30 , c = 40 ;
System.out.println( middleOfThree(a, b, c) );
}
}
// This code is contributed by rishabh_jain

Python3

# Python3 program to find middle
# of three distinct numbers
def middleOfThree(a, b, c):
# Checking for b
if ((a < b and b < c) or (c < b and b < a)) :
return b;
# Checking for a
if ((b < a and a < c) or (c < a and a < b)) :
return a;
else :
return c
# Driver Code
a = 20
b = 30
c = 40
print (middleOfThree(a, b, c))
# This code is contributed by rishabh_jain

C #

// C# program to find middle of
// three distinct numbers
using System;
class Middle
{
// Function to find the middle of three number
public static int middleOfThree( int a, int b,
int c)
{
// Checking for b
if ((a < b && b < c) || (c < b && b < a))
return b;
// Checking for a
else if ((b < a && a < c) || (c < a && a < b))
return a;
else
return c;
}
// Driver code
public static void Main()
{
int a = 20, b = 30, c = 40;
Console.WriteLine( middleOfThree(a, b, c) );
}
}
// This code is contributed by vt_m

PHP

<?php
// PHP program to find middle
// of three distinct numbers
function middleOfThree( $a , $b , $c )
{
// Checking for b
if (( $a < $b && $b < $c ) or
( $c < $b && $b < $a ))
return $b ;
// Checking for a
else if (( $b < $a and $a < $c ) or
( $c < $a and $a < $b ))
return $a ;
else
return $c ;
}
// Driver Code
$a = 20;
$b = 30;
$c = 40;
echo middleOfThree( $a , $b , $c );
// This code is contributed by anuj_67.
?>

Javascript

<script>
// Javascript program to find middle of three distinct
// numbers
function middleOfThree( a, b, c)
{
// Checking for b
if ((a < b && b < c) || (c < b && b < a))
return b;
// Checking for a
else if ((b < a && a < c) || (c < a && a < b))
return a;
else
return c;
}
// driver code
let a = 20, b = 30, c = 40;
document.write(middleOfThree(a, b, c));
</script>

Выход :

 30

Но использованный выше подход неэффективен из-за лишних сравнений, которые можно легко минимизировать. Если первая часть ложна, она выполнит оставшуюся половину, чтобы проверить условие. Эта проблема остается тем же , если мы проверяем , на также.
Лучший подход (требует меньшего сравнения):

Выход:

 30

Такой подход эффективен и требует меньшего количества сравнений. Внешний цикл IF будет выполнен, только если a> b, в противном случае будет выполнен внешний цикл ELSE.
Другой эффективный подход:

C ++

// CPP program to find middle of three distinct
// numbers
#include <bits/stdc++.h>
using namespace std;
// Function to find the middle of three number
int middleOfThree( int a, int b, int c)
{
// x is positive if a is greater than b.
// x is negative if b is greater than a.
int x = a - b;
int y = b - c; // Similar to x
int z = a - c; // Similar to x and y.
// Checking if b is middle (x and y both
// are positive)
if (x * y > 0)
return b;
// Checking if c is middle (x and z both
// are positive)
else if (x * z > 0)
return c;
else
return a;
}
// Driver Code
int main()
{
int a = 20, b = 30, c = 40;
cout << middleOfThree(a, b, c);
return 0;
}

Джава

//java program to find middle of three distinct
// numbers
import java.util.*;
class Middle
{
// Function to find the middle of three number
public static int middleOfThree( int a, int b,
int c)
{
// x is positive if a is greater than b.
// x is negative if b is greater than a.
int x = a - b;
int y = b - c; // Similar to x
int z = a - c; // Similar to x and y.
// Checking if b is middle (x and y
// both are positive)
if (x * y > 0 )
return b;
// Checking if c is middle (x and z
// both are positive)
else if (x * z > 0 )
return c;
else
return a;
}
// driver code
public static void main(String[] args)
{
int a = 20 , b = 30 , c = 40 ;
System.out.println( middleOfThree(a, b, c) );
}
}
// This code is contributed by rishabh_jain

Python3

# Python3 program to find middle
# of three distinct numbers
# Function to find the middle of three number
def middleOfThree(a, b, c) :
# x is positive if a is greater than b.
# x is negative if b is greater than a.
x = a - b
# Similar to x
y = b - c
# Similar to x and y.
z = a - c
# Checking if b is middle (x and y
# both are positive)
if x * y > 0 :
return b
# Checking if c is middle (x and z
# both are positive)
elif (x * z > 0 ) :
return
else :
return a
# Driver Code
a = 20
b = 30
c = 40
print (middleOfThree(a, b, c))
# This code is contributed by rishabh_jain

C #

//C# program to find middle of three distinct
// numbers
using System;
class Middle
{
// Function to find the middle of three number
public static int middleOfThree( int a, int b,
int c)
{
// x is positive if a is greater than b.
// x is negative if b is greater than a.
int x = a - b;
// Similar to x
int y = b - c;
// Similar to x and y.
int z = a - c;
// Checking if b is middle (x and y
// both are positive)
if (x * y > 0)
return b;
// Checking if c is middle (x and z
// both are positive)
else if (x * z > 0)
return c;
else
return a;
}
// Driver code
public static void Main()
{
int a = 20, b = 30, c = 40;
Console.WriteLine( middleOfThree(a, b, c) );
}
}
// This code is contributed by vt_m

PHP

<?php
// PHP program to find middle
// of three distinct numbers
// Function to find the
// middle of three number
function middleOfThree( $a , $b , $c )
{
// x is positive if a
// is greater than b.
// x is negative if b
// is greater than a.
$x = $a - $b ;
// Similar to x
$y = $b - $c ;
// Similar to x and y.
$z = $a - $c ;
// Checking if b is
// middle (x and y both
// are positive)
if ( $x * $y > 0)
return $b ;
// Checking if c is
// middle (x and z both
// are positive)
else if ( $x * $z > 0)
return $c ;
else
return $a ;
}
// Driver Code
$a = 20;
$b = 30;
$c = 40;
echo middleOfThree( $a , $b , $c );
// This code is contributed by anuj_67.
?>

Javascript

<script>
// javascript program to find middle of
// three distinct numbers
// Function to find the middle of three number
function middleOfThree(a, b, c)
{
// x is positive if a is greater than b.
// x is negative if b is greater than a.
let x = a - b;
let y = b - c; // Similar to x
let z = a - c; // Similar to x and y.
// Checking if b is middle (x and y
// both are positive)
if (x * y > 0)
return b;
// Checking if c is middle (x and z
// both are positive)
else if (x * z > 0)
return c;
else
return a;
}
// Driver code
let a = 20, b = 30, c = 40;
document.write( middleOfThree(a, b, c) );
</script>

Выход :

 30

Вниманию читателя! Не прекращайте учиться сейчас. Освойте все важные концепции DSA с помощью самостоятельного курса DSA по доступной для студентов цене и будьте готовы к работе в отрасли. Чтобы завершить подготовку от изучения языка к DS Algo и многому другому, см. Полный курс подготовки к собеседованию .

Если вы хотите посещать живые занятия с отраслевыми экспертами, пожалуйста, обращайтесь к Geeks Classes Live и Geeks Classes Live USA.