So I'm attempting a coding exercise, and I can't seem to find the problem. I need to pull the median from an array. If the array is an even length, I need the average of two values.
const N = parseInt(readline());
var inputs = readline().split(' ');
for (let i = 0; i < N; i++) {
const X = parseInt(inputs[i]);
}
var arr = inputs.sort((a, b) => a - b);
if (arr.length % 2 === 0)
{
console.error(arr);
console.error(arr[arr.length / 2 - 1]);
console.error(arr[arr.length / 2]);
var a = arr[arr.length / 2 - 1];
var b = arr[arr.length / 2];
var ans = (a + b) / 2;
console.log(ans);
}
else console.log(arr[Math.floor(arr.length/2)]);
CONSOLE OUTPUT: [ '1', '2', '3', '4', '5', '6', '7', '8', '9', '10' ] 5 6 28
So from the console output, my array is sorted properly. Next, I'm pulling out the two medians correctly. My a is indeed 5, and my b is indeed 6. But adding them with (a + b) / 2 suddenly turns into 28... Why?
56/2=28