Created
May 27, 2014 10:34
-
-
Save aprell/2e3968788ae34f3ec861 to your computer and use it in GitHub Desktop.
Sorting an array in AWK
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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