Search code examples
arraysswiftswift3median

Get median of array


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?


Solution

  • 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