find the median of all values in a map in swift

To find the median of all values in a map in Swift, you need to follow these steps:

  1. Get all the values of the map and sort them in ascending order.
  2. Find the middle index of the sorted values.
  3. If the count of the sorted values is odd, return the value at the middle index.
  4. If the count of the sorted values is even, return the average of the two values at the middle indices.

Here's the implementation of the above algorithm:

main.swift
func medianOfMapValues<T: Comparable>(_ map: [AnyHashable: T]) -> T? {
    let sortedValues = map.values.sorted()
    let count = sortedValues.count
    guard count > 0 else { return nil }
    let middleIndex = (count - 1) / 2
    if count % 2 == 0 {
        let leftValue = sortedValues[middleIndex]
        let rightValue = sortedValues[middleIndex + 1]
        return (leftValue + rightValue) / 2
    } else {
        return sortedValues[middleIndex]
    }
}
462 chars
14 lines

You can use this function like this:

main.swift
let map = ["a": 10, "b": 20, "c": 30, "d": 40]
if let median = medianOfMapValues(map) {
    print("Median: ", median)
}
120 chars
5 lines

Output:

main.swift
Median:  25.0
14 chars
2 lines

gistlibby LogSnag