Open In App

JavaScript Program to Find the Middle of Three

Last Updated : 19 Oct, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we are going to implement an algorithm through which we can find the number that lies in the middle. Basically, we have three numbers, and the desired number will lie in the middle of the other two numbers according to the number line.

Examples:

Input : a = 2, b = 3, c = 4
Output : 3
Input : a = 50, n = 75, c = 100
Output : 75

Using Naive Approach

In this approach, we are comparing each number with the others using an if-else statement with appropriate conditions and also returning the number according to them.

Example: The below example shows the use of the above-explained appraoch.

Javascript




// Javascript program to find middle 
// of three distinct values
  
function mid3(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 = 15,
    b = 254,
    c = 39;
console.log(mid3(a, b, c));


Output

39

Using Efficient Approach

The expression (a > b and b > c) or (a < b and b < c) can also be interpreted as a – b > 0, b – c > 0, or a – b < 0, b – c < 0, indicating that the differences between a and b and between b and c should have the same sign. Therefore, if we let x = a – b and y = b – c, and both x and y have the same sign, their result will always be positive, making b the middle element.

Example: The below example shows the use of the above-explained appraoch.

Javascript




// Javascript program to find middle of
// three distinct numbers
  
// Function to find the middle of three number
function mid3(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 = 389,
    b = 287,
    c = 416;
console.log(mid3(a, b, c));


Output

389


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads