I have an array that looks like this:
let arr = [1,2,3,4,5,6,7,8,9]
I know you can get min
and max
by:
let min = arr.min()
let max = arr.max()
But how do you get the median?
To calculate the median first we need to sort the list in ascending or descending order. If the number of elements are even, then the median will the average of two numbers in the middle. But the number is odd then the middle element of the array after sorting will be considered as the median.
To find the median, calculate the mean by adding together the middle values and dividing them by two.
If the array length is even then median will be arr[(arr. length)/2] +arr[((arr. length)/2)+1]. If the array length is odd then the median will be a middle element.
Median formula when a data set is even Determine if the number of values, n, is even. Locate the two numbers in the middle of the data set. Find the average of the two middle numbers by adding them together and dividing the sum by two. The result of this average is the median.
To get the median
you can use the following:
let median = arr.sorted(by: <)[arr.count / 2]
In your case it will return 5
.
As @Nirav pointed out [1,2,3,4,5,6,7,8]
will return 5
but should return 4.5
.
Use this instead:
func calculateMedian(array: [Int]) -> Float {
let sorted = array.sorted()
if sorted.count % 2 == 0 {
return Float((sorted[(sorted.count / 2)] + sorted[(sorted.count / 2) - 1])) / 2
} else {
return Float(sorted[(sorted.count - 1) / 2])
}
}
Usage:
let array = [1,2,3,4,5,6,7,8]
let m2 = calculateMedian(array: array) // 4.5
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With