My approach to solving HackerRank’s Find the Median code challenge.
Problem
The median of a list of numbers is essentially its middle element after sorting. The same number of elements occur after it as before. Given a list of numbers with an odd number of elements, find the median?
Example
arr = [5, 3, 1, 2, 4]
The sorted array arr = [1, 2, 3, 4, 5]. The middle element and the median is 3.
Input format
The first line contains the integer n, the size of arr.
The second line contains n space-separated integers arr[i].
Returns
int: the median of the array.
Sample input
7
0 1 2 4 6 5 3
Sample output
3
Solution
We start by sorting our given array in ascending order and saving the results as a sorted array (strArr) variable.
After that, we find the array's middle point by dividing the array's length by 2 and using Math.floor() to round up the number.
Then we check to see if the array's length is even or odd and return the results based on the evaluation.
function findMedian(arr) {
const srtArr = arr.sort((a, b) => a - b);
const mid = Math.floor(srtArr.length / 2);
if (srtArr.length % 2 === 0) {
return (srtArr[mid - 1] + srtArr[mid]) / 2;
}
return srtArr[mid];
}