find the median of all elements in an array in swift

One way to find the median of all elements in an array in Swift is to sort the array and then take the middle element (or the average of the two middle elements if the array length is even). Here's an example:

main.swift
func findMedian(in array: [Int]) -> Double? {
    let sortedArray = array.sorted()
    let count = sortedArray.count
    
    if count == 0 {
        return nil
    } else if count % 2 == 0 {
        // average of two middle elements
        let midIndex = count / 2
        return Double(sortedArray[midIndex] + sortedArray[midIndex-1]) / 2.0
    } else {
        // middle element
        let midIndex = count / 2
        return Double(sortedArray[midIndex])
    }
}

// example usage
let nums = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
if let median = findMedian(in: nums) {
    print("Median is \(median)")
} else {
    print("Array is empty")
}
643 chars
25 lines

This function takes an array of Int, sorts it, and returns the median as a Double. If the array is empty, it returns nil.

gistlibby LogSnag