How to resolve the algorithm Averages/Median step by step in the jq programming language
How to resolve the algorithm Averages/Median step by step in the jq programming language
Table of Contents
Problem Statement
Write a program to find the 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 element(s) in the middle. Sorting would take at least O(n logn). Another approach would be to build a priority queue from the elements, and then extract half of the elements to get to the middle element(s). This would also take O(n logn). The best solution is to use the selection algorithm to find the median in O(n) time. Quickselect_algorithm
Let's start with the solution:
Step by Step solution about How to resolve the algorithm Averages/Median step by step in the jq programming language
Source code in the jq programming language
def median:
length as $length
| sort as $s
| if $length == 0 then null
else ($length / 2 | floor) as $l2
| if ($length % 2) == 0 then
($s[$l2 - 1] + $s[$l2]) / 2
else $s[$l2]
end
end ;
[4.1, 5.6, 7.2, 1.7, 9.3, 4.4, 3.2]
[4.1, 7.2, 1.7, 9.3, 4.4, 3.2]
$ jq -f median.jq in.dat
4.4
4.25
You may also check:How to resolve the algorithm Evaluate binomial coefficients step by step in the Maple programming language
You may also check:How to resolve the algorithm Tonelli-Shanks algorithm step by step in the Java programming language
You may also check:How to resolve the algorithm Rosetta Code/Find bare lang tags step by step in the Nim programming language
You may also check:How to resolve the algorithm GUI component interaction step by step in the Scala programming language
You may also check:How to resolve the algorithm Factorial step by step in the LiveCode programming language