Skip to content

Instantly share code, notes, and snippets.

@aprell
Created May 27, 2014 10:34
Show Gist options
  • Save aprell/2e3968788ae34f3ec861 to your computer and use it in GitHub Desktop.
Save aprell/2e3968788ae34f3ec861 to your computer and use it in GitHub Desktop.
Sorting an array in AWK
#!/usr/bin/awk -f
BEGIN {
i = 0
}
{
numbers[i++] = $1
}
END {
n = asort(numbers)
# After the call to asort(), numbers is indexed from 1 to n
for (i = 1; i <= n; i++) {
print numbers[i]
}
# Alternatively, we can write:
# for (i in numbers) print numbers[i]
print "Minimum:", numbers[1]
print "Maximum:", numbers[n]
print "Median:", n % 2 == 1 ? numbers[int(n/2)+1] \
: (numbers[int(n/2)] + numbers[int(n/2)+1]) / 2
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment