- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
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
Advertisements