Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Middle of three elements - JavaScript
We are required to write a JavaScript function that takes in three unsorted numbers and returns the middlemost of them using minimum number of comparisons.
For example: If the numbers are ?
34, 45, 12
Then our function should return the following ?
34
Algorithm Explanation
The algorithm uses mathematical differences to determine the middle element without explicit sorting. By calculating differences between pairs and checking their signs, we can identify the middle value efficiently.
Example
Following is the code ?
const num1 = 34;
const num2 = 45;
const num3 = 12;
const 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;
let z = a - c;
// Checking if b is middle (x and y both
// are positive or both negative)
if (x * y > 0) {
return b;
} else if (x * z > 0) {
return c;
} else {
return a;
}
};
console.log(middleOfThree(num1, num2, num3));
Output
34
How It Works
The algorithm works by analyzing the relationships between the three numbers:
- x = a - b: Positive if a > b, negative if b > a
- y = b - c: Positive if b > c, negative if c > b
- z = a - c: Positive if a > c, negative if c > a
If x * y > 0, both differences have the same sign, meaning b is the middle element. Similarly, checking x * z helps identify if c is middle, otherwise a is middle.
Additional Examples
// Test with different arrangements
console.log("Middle of 10, 5, 8:", middleOfThree(10, 5, 8));
console.log("Middle of 1, 3, 2:", middleOfThree(1, 3, 2));
console.log("Middle of 7, 2, 9:", middleOfThree(7, 2, 9));
console.log("Middle of equal values 5, 5, 3:", middleOfThree(5, 5, 3));
Middle of 10, 5, 8: 8 Middle of 1, 3, 2: 2 Middle of 7, 2, 9: 7 Middle of equal values 5, 5, 3: 5
Conclusion
This algorithm efficiently finds the middle element using only three comparisons through mathematical differences. It's more efficient than sorting all three numbers and works correctly even with duplicate values.
