Is there a median function in the C++ library?

There’s no need to use a function. To find the median of a list with an odd number of items, just do

cout << sortedArray[size/2];

where sortedArray is the array and size is the size of the array. For an array with an even number, you should just do something like this

cout << (sortedArray[size/2] + sortedArray[(size/2) - 1])/2

In other words, take the average of the n/2 element and the n/2-1 element.

If you don’t know the size, you need to loop through the array and count how many elements there are. Doing it with decimals is irrelevant because the size of an array is always a whole number.

Leave a Comment