swift
Parameters: [Int]
An array of integer numbers
Returns: Int or Double, the median of the input array
This function takes an array of integers as input and returns the median of the array.
Hello Programmer! In this post, we outline the necessary steps to program a function for finding the median of an array in Swift. This can be a handy function when dealing with statistical data. With this guide, you don't need advanced knowledge, as everything is laid out for you to follow. Let's get your hands on some Swift code!
The task is to find the median of an array of integers. In statistics, the median is the value separating the higher half from the lower half of a data sample. If we sort the array in non-decreasing order, the median is the middle element if the array size is odd, and average of two middle numbers if the size is even.
Here is the initial function declaration:
func findMedian(array: [Int]) -> Double {}
Before we proceed, we should handle the case where the input array is empty. In this case, we can return 0.0.
func findMedian(array: [Int]) -> Double {
if array.isEmpty {
return 0.0
}
}
The next step is to sort the array in non-decreasing order. We can use the built-in sort
function in Swift.
func findMedian(array: [Int]) -> Double {
if array.isEmpty {
return 0.0
}
let sortedArray = array.sorted()
}
Now, we can find the median based on the length of the sorted array. Remember that array indices start at 0.
func findMedian(array: [Int]) -> Double {
if array.isEmpty {
return 0.0
}
let sortedArray = array.sorted()
let middleIndex = sortedArray.count / 2
if sortedArray.count % 2 == 0 {
return Double(sortedArray[middleIndex - 1] + sortedArray[middleIndex]) / 2.0
} else {
return Double(sortedArray[middleIndex])
}
}
This function now successfully finds the median of an array in Swift. It handles empty arrays, and works correctly for both even and odd length arrays. The sort function has a time complexity of O(n log n) and finding the median has a time complexity of O(1), so the overall time complexity is O(n log n).
The mathematical principle behind this function is finding the 'middle' number in a ordered set of numbers. If the set has an odd number of observations, the middle value is defined clear. If the set has an even number of observations, the median value is calculated as the average of the two middle numbers.
Learn more