Averages/Median: Difference between revisions

Content deleted Content added
Added Scala
Line 541:
(srtd[(alen-1)/2] + srtd[alen/2]) / 2.0
end</lang>
 
=={{header|Scala}}==
This only works on Scala 2.8. See the Scala discussion on [[Mean]] for more information.
 
<lang scala>def median[T](s: Seq[T])(implicit n: Fractional[T]) = {
import n._
val (lower, upper) = s.sortWith(_<_).splitAt(s.size / 2)
if (s.size % 2 == 0) (lower.last + upper.head) / fromInt(2) else upper.head
}</lang>
 
This isn't really optimal. The methods <tt>splitAt</tt> and <tt>last</tt> are O(n/2)
on many sequences, and then there's the lower bound imposed by the sort. Finally,
we call <tt>size</tt> two times, and it can be O(n).
 
=={{header|Scheme}}==