Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get median of array

I have an array that looks like this:

let arr = [1,2,3,4,5,6,7,8,9]

I know you can get min and max by:

let min = arr.min()
let max = arr.max()

But how do you get the median?

like image 978
John S Avatar asked Jun 09 '17 05:06

John S


People also ask

How do you find the median of an array in C?

To calculate the median first we need to sort the list in ascending or descending order. If the number of elements are even, then the median will the average of two numbers in the middle. But the number is odd then the middle element of the array after sorting will be considered as the median.

How do you extract median?

To find the median, calculate the mean by adding together the middle values and dividing them by two.

What is the median of an array JS?

If the array length is even then median will be arr[(arr. length)/2] +arr[((arr. length)/2)+1]. If the array length is odd then the median will be a middle element.

What is the formula to find the median?

Median formula when a data set is even Determine if the number of values, n, is even. Locate the two numbers in the middle of the data set. Find the average of the two middle numbers by adding them together and dividing the sum by two. The result of this average is the median.


1 Answers

To get the median you can use the following:

let median = arr.sorted(by: <)[arr.count / 2]

In your case it will return 5.

As @Nirav pointed out [1,2,3,4,5,6,7,8] will return 5 but should return 4.5.

Use this instead:

func calculateMedian(array: [Int]) -> Float {
    let sorted = array.sorted()
    if sorted.count % 2 == 0 {
        return Float((sorted[(sorted.count / 2)] + sorted[(sorted.count / 2) - 1])) / 2
    } else {
        return Float(sorted[(sorted.count - 1) / 2])
    }
}

Usage:

let array = [1,2,3,4,5,6,7,8]
let m2 = calculateMedian(array: array) // 4.5
like image 95
Rashwan L Avatar answered Oct 16 '22 10:10

Rashwan L