Created
March 25, 2014 15:18
-
-
Save rizo/9764024 to your computer and use it in GitHub Desktop.
Median implementation in D.
This file contains hidden or 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
| import std.stdio, std.algorithm; | |
| T median(T)(T[] nums) /*pure nothrow*/ { | |
| nums.sort(); | |
| if (nums.length & 1) | |
| return nums[$ / 2]; | |
| else | |
| return (nums[$ / 2 - 1] + nums[$ / 2]) / 2.0; | |
| } | |
| void main() { | |
| auto a1 = [5.1, 2.6, 6.2, 8.8, 4.6, 4.1]; | |
| writeln("Even median: ", median(a1)); | |
| auto a2 = [5.1, 2.6, 8.8, 4.6, 4.1]; | |
| writeln("Odd median: ", median(a2)); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment