find the median from an array of doubles in swift

To find the median from an array of doubles in Swift, we can use the following steps:

  1. Sort the array in ascending or descending order
  2. Calculate the middle index of the array
  3. Check if the array has an odd or even number of elements
  4. If the array has an odd number of elements, return the middle element
  5. If the array has an even number of elements, return the average of the two middle elements

Here's the implementation:

main.swift
func findMedian(_ arr: [Double]) -> Double {
    let sortedArr = arr.sorted()
    let middleIndex = sortedArr.count / 2

    if sortedArr.count % 2 == 0 {
        // even number of elements
        let middleElement1 = sortedArr[middleIndex - 1]
        let middleElement2 = sortedArr[middleIndex]
        return (middleElement1 + middleElement2) / 2
    } else {
        // odd number of elements
        return sortedArr[middleIndex]
    }
}
444 chars
15 lines

We can call this function with an array of doubles to get the median:

main.swift
let arr: [Double] = [1.0, 2.0, 3.0, 4.0, 5.0]
let median = findMedian(arr) // median is 3.0
92 chars
3 lines

gistlibby LogSnag