-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathmedian
executable file
·79 lines (67 loc) · 1.92 KB
/
median
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
#!/usr/bin/awk -f
#
# Copyright (c) 2012,2014 Douglas G. Scofield, Uppsala University
#
# This code is covered by the Gnu GPLv2, please see LICENSE.
# Bugs and suggestions to https://github.com/douglasgscofield/tinyutils/issues.
#
# Compute the median of a set of numbers
#
# CHANGELOG
# 2014-05-27 : don't quit on missing-column error
# 2012-12-03 : clean the script up a bit
BEGIN {
# parameters
n = 0;
header = 0; # does the input have a header? if so how many lines?
skip_comment = 1; # skip '#' lines on input
col = 1; # which column do we operate on?
}
# quicksort array values, from http://awk.info/?quicksort
# gawk provides asort() but we're living gawk free these days
function qsort(array, left, right, i, last)
{
if (left >= right)
return;
swap(array, left, left+int((right - left + 1) * rand()));
last = left;
for (i = left + 1; i <= right; ++i)
if (array[i] < array[left])
swap(array, ++last, i);
swap(array, left, last);
qsort(array, left, last - 1);
qsort(array, last + 1, right);
}
# swap two values, utility function for qsort()
function swap(array, i, j, t)
{
t = array[i]; array[i] = array[j]; array[j] = t;
}
# compute the median value of values within array, which has size array_size
function compute_median(array, array_size, ans)
{
qsort(array, 1, array_size);
if (array_size == 1) {
ans = array[array_size];
} else if ((array_size % 2) == 1) {
ans = array[int(array_size / 2)];
} else {
ans = (array[array_size / 2] + array[array_size / 2 + 1]) / 2;
}
return ans;
}
{
if (NR <= header) { print; next; }
if (skip_comment && $0 ~ /^#/) { print; next; }
if (NF < col) {
print "on input line " NR " missing requested column" > "/dev/stderr";
next;
}
a[++n] = $(col);
}
END {
if (n)
print compute_median(a, n);
}