-1

I want to have an awk function to compute the median of an array (may not be sorted).

median of column with awk

The above is a similar post but it is not the same as this one because the input on the above post is a sorted stream.

Could anybody show me the function to compute the median of an array?

user1424739
  • 11,937
  • 17
  • 63
  • 152
  • Who deleted the previous comments here. I am sick of the censorship at stackoverflow. Stackoverflow is self-serving and any comments revealing about the truth that it is self-serving frequently got deleted on stackoverflow website. – user1424739 Jun 24 '21 at 21:42

1 Answers1

0

I got the following solution. I am not sure if it would fail in a corner case. If it does, please let me know.

function median(x,        n, d) {
    n = asort(x, d, "@val_num_asc")
    if(n == 0) return "NA"
    if(n%2) {
        return d[(n+1)/2]
    } else {
        return (d[n/2] + d[n/2+1])/2
    }
}
user1424739
  • 11,937
  • 17
  • 63
  • 152