Skip to content

Instantly share code, notes, and snippets.

@rizo
Created March 25, 2014 15:18
Show Gist options
  • Select an option

  • Save rizo/9764024 to your computer and use it in GitHub Desktop.

Select an option

Save rizo/9764024 to your computer and use it in GitHub Desktop.
Median implementation in D.
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