-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfineMedian.js
More file actions
29 lines (23 loc) · 978 Bytes
/
Copy pathfineMedian.js
File metadata and controls
29 lines (23 loc) · 978 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
/**
* -------------------------------------------------------
* Programming Question : Find Median
* -------------------------------------------------------
**/
// Q. Write a JavaScript function findMedian(arr) thatt takes an array of numbers as input and returns the median value. If the array has an even number of elements, return the average of the two middle values.
//? Todo Tips:
//? Sort the array in ascenending order.
//? If the array has an even number of elements, the median is the middle element.
//? If the array has an odd number of elements, the median is the average of the two middle elements.
function findMedian(arr) {
arr = arr.sort((a,b) => a-b);
console.log(arr);
let mid = Math.floor(arr.length / 2);
if(arr.length%2 === 0){
return (arr[mid] + arr[mid - 1]) / 2;
}else{
return arr[mid];
}
}
console.log(findMedian([3, 2, 1, 5, 4]));
console.log(findMedian([1,3,5,7,9,11]));
console.log(findMedian([2,4,6,8]));