JavaScript Program to Find the Middle of Three
Last Updated :
19 Oct, 2023
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
function mid3(a, b, c) {
if (
(a < b && b < c) ||
(c < b && b < a)
)
return b;
else if (
(b < a && a < c) ||
(c < a && a < b)
)
return a;
else return c;
}
let a = 15,
b = 254,
c = 39;
console.log(mid3(a, b, c));
|
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
function mid3(a, b, c) {
let x = a - b;
let y = b - c;
let z = a - c;
if (x * y > 0) return b;
else if (x * z > 0) return c;
else return a;
}
let a = 389,
b = 287,
c = 416;
console.log(mid3(a, b, c));
|
Share your thoughts in the comments
Please Login to comment...