Averages/Median: Difference between revisions

Content added Content deleted
m (added whitespace before the TOC, added a ;See also: (bold) header.)
Line 1: Line 1:
{{task|Probability and statistics}}
{{task|Probability and statistics}}Write a program to find the [[wp:Median|median]] value of a vector of floating-point numbers. The program need not handle the case where the vector is empty, but ''must'' handle the case where there are an even number of elements. In that case, return the average of the two middle values.

Write a program to find the [[wp:Median|median]] value of a vector of floating-point numbers.

The program need not handle the case where the vector is empty, but ''must'' handle the case where there are an even number of elements. In that case, return the average of the two middle values.


There are several approaches to this. One is to sort the elements, and then pick the one(s) in the middle. Sorting would take at least <span style="font-family: serif">O(''n'' log''n'')</span>. Another would be to build a priority queue from the elements, and then extract half of the elements to get to the middle one(s). This would also take <span style="font-family: serif">O(''n'' log''n'')</span>. The best solution is to use the [[wp:Selection algorithm|selection algorithm]] to find the median in <span style="font-family: serif">O(''n'')</span> time.
There are several approaches to this. One is to sort the elements, and then pick the one(s) in the middle. Sorting would take at least <span style="font-family: serif">O(''n'' log''n'')</span>. Another would be to build a priority queue from the elements, and then extract half of the elements to get to the middle one(s). This would also take <span style="font-family: serif">O(''n'' log''n'')</span>. The best solution is to use the [[wp:Selection algorithm|selection algorithm]] to find the median in <span style="font-family: serif">O(''n'')</span> time.



See also: [[Mean]], [[Mode]]
;See also:
* [[Mean]]
* [[Mode]]
<br><br>

=={{header|Ada}}==
=={{header|Ada}}==
<lang ada>with Ada.Text_IO, Ada.Float_Text_IO;
<lang ada>with Ada.Text_IO, Ada.Float_Text_IO;