Calculate Median Number in Array

Hello,

Looking for some guidance. What is the easiest way to calculate a median number in an array? Is there a library that makes this easy?

I am taking 10 readings from a range sensor.

Values Recorded 20, 19, 20, 2, 19, 20 , 21, 20, 22, 20
Median 20

Thanks

1 Like

To find the median you need to sort the array, and if there are an odd number of entries, choose the middle value. If even, average the two values on either side of the middle. There are indeed Arduino libraries for that.

In the Arduino IDE, select tools>manage libraries and enter "median" in the search box. Pick one and install.

1 Like

jremington:
To find the median you need to sort the array, and if there are an odd number of entries, choose the middle value. If even, average the two values on either side of the middle. There are indeed Arduino libraries for that.

In the Arduino IDE, select tools>manage libraries and enter "median" in the search box. Pick one and install.

You don't actually need to sort an array to find the median. You can do it in linear time: