Middle of three elements - JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

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

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.
   x = a - b;
   y = b - c;
   z = a - c;
   // Checking if b is middle (x and y both
   // are positive)
   if (x * y > 0) {
      return b;
   }else if (x * z > 0){
      return c;
   }else{
      return a;
   }
};
console.log(middleOfThree(num1, num2, num3));

Output

Following is the output in the console −

34
raja
Published on 16-Sep-2020 09:26:45
Advertisements