My approach to solving HackerRank’s Find the Median code challenge.
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?
arr = [5, 3, 1, 2, 4]
The sorted array arr = [1, 2, 3, 4, 5]
. The middle element and the median is 3
.
The first line contains the integer n
, the size of arr
.
The second line contains n
space-separated integers arr[i]
.
int
: the median of the array.
1720 1 2 4 6 5 3
13
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.
1function findMedian(arr) {2 const srtArr = arr.sort((a, b) => a - b);3 const mid = Math.floor(srtArr.length / 2);4
5 if (srtArr.length % 2 === 0) {6 return (srtArr[mid - 1] + srtArr[mid]) / 2;7 }8
9 return srtArr[mid];10}
Sign up to get updates when I write something new. No spam ever.
Subscribe to my Newsletter