- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
- Related Articles
- Middle of three using minimum comparisons in C++
- Python – K middle elements
- Sorting array of exactly three unique repeating elements in JavaScript
- Adding elements in the middle of an ArrayList in Java
- Add elements at the middle of a Vector in Java
- Name the three tiny bones present in the middle part of ear.
- Finding three elements with required sum in an array in JavaScript
- How to select the middle of an array? - JavaScript
- Check if three consecutive elements in an array is identical in JavaScript
- Find the middle element of an array using recursion JavaScript
- Insert value in the middle of every value inside array JavaScript
- JavaScript: How to Find the Middle Element of a Linked List?
- Maximum possible middle element of the array after deleting exactly k elements in C++
- How to find a group of three elements in an array whose sum equals some target sum JavaScript
- Find three closest elements from given three sorted arrays in C++

Advertisements