need to find the median of a dynamically allocated array

I am new to C++ and am struggling with it.
I have a homework problem that requires that I make a dynamically allocated array, calculate the average and then find the median.
I have the array (and I got it sorted) and I have the average, what I can't figure out is how to get the median.
Any help would be greatly appreciated thank you.
sort the input from lowest to highest or highest to lowest, doesn't matter.

median = the item in the item in the mid, which has the index size() / 2
Last edited on
median = the item in the item in the mid, which has the index size() / 2


Not quite, if number of objects is even then the median is the mean of the two middle objects. If number of objects is odd, then median is the middle object.

If odd, divide size by two and round up. That'll be the index you want.

If even, the two indices you're looking for are size() / 2, and size() / 2 + 1. Then find the mean of those two.
Thank you both I did have a general idea on how to get the median what I don't know is how to implement it with an array that can vary in size, specifically a dynamically allocated array.
Can you not use std::vector? If not, you still have a variable somewhere keeping track of the size.
If odd, divide size by two and round up. That'll be the index you want.

Actually, you want to divide by two and round down, since indexing begins at 0.


If even, the two indices you're looking for are size() / 2, and size() / 2 + 1. Then find the mean of those two

Similarly, you want the elements at size/2 and (size/2)-1.
Ah good call. Didn't account for that
Topic archived. No new replies allowed.