Skip to content

Instantly share code, notes, and snippets.

@mntone
Created September 18, 2019 02:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mntone/8819d101b7f4a8378276d6a17ae5a349 to your computer and use it in GitHub Desktop.
Save mntone/8819d101b7f4a8378276d6a17ae5a349 to your computer and use it in GitHub Desktop.
Array+Median.swift under MIT license
// Copyright (C) 2019 mntone. All rights reserved.
// MIT license
extension Array where Array.Element: Numeric & Comparable {
@inlinable
public func medianFast() -> Element {
return sorted(by: <)[count / 2]
}
}
extension Array where Array.Element: BinaryInteger {
@inlinable
public func median() -> Element {
let sortedArray = sorted(by: <)
let count = self.count
if count % 2 == 0 {
let halfCount = count / 2
return Element(Float32(0.5) * Float32(sortedArray[halfCount - 1] + sortedArray[halfCount]))
} else {
return sortedArray[count / 2]
}
}
}
extension Array where Array.Element: FloatingPoint {
@inlinable
public func median() -> Element {
let sortedArray = sorted(by: <)
let count = self.count
if count % 2 == 0 {
let halfCount = count / 2
return (sortedArray[halfCount - 1] + sortedArray[halfCount]) / Element(2)
} else {
return sortedArray[count / 2]
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment