find the median of a list of numbers in swift

To find the median of a list of numbers in Swift, follow these steps:

  1. First, sort the array of numbers in ascending order.
  2. Check if the array has an odd or even number of elements.
  3. If the array has an odd number of elements, return the middle element.
  4. If the array has an even number of elements, take the average of the two middle elements.

Here's the Swift code to find the median of an array of numbers:

main.swift
func findMedian(_ nums: [Double]) -> Double {
    let sortedNums = nums.sorted()
    let count = sortedNums.count
    if count % 2 == 0 {
        let midIndex1 = count / 2 - 1
        let midIndex2 = count / 2
        return (sortedNums[midIndex1] + sortedNums[midIndex2]) / 2
    } else {
        let midIndex = count / 2
        return sortedNums[midIndex]
    }
}
367 chars
13 lines

In this code, we use the sorted() method of the array type to sort the input numbers. Then, we check if the count of the array is even or odd, and calculate the median accordingly. If it's even, we take the midIndex1 and midIndex2, which are the indices of the two middle elements. We then take the average of these two values, which gives us the median.

gistlibby LogSnag