Created
September 18, 2019 02:48
-
-
Save mntone/8819d101b7f4a8378276d6a17ae5a349 to your computer and use it in GitHub Desktop.
Array+Median.swift under MIT license
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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