Get median of array Get median of array arrays arrays

Get median of array


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


The median is defined as the number in the middle of the sequence. If there is not one middle number, then it's the average of the two middle numbers.

extension Array where Element == Int {    func median() -> Double {        let sortedArray = sorted()        if count % 2 != 0 {            return Double(sortedArray[count / 2])        } else {            return Double(sortedArray[count / 2] + sortedArray[count / 2 - 1]) / 2.0        }    }}


Note that if the array is empty, the median is undefined. So a safe median function returns an optional, just like the min() and max() built-in methods do.

extension Array where Element == Int {    func median() -> Double? {        guard count > 0  else { return nil }        let sortedArray = self.sorted()        if count % 2 != 0 {            return Double(sortedArray[count/2])        } else {            return Double(sortedArray[count/2] + sortedArray[count/2 - 1]) / 2.0        }    }}

With that defined, you can write:

if let median = arr.median() {    // do something}