Shell 脚本:在不排序的整数序列中查找最大值 [英] Shell script: find maximum value in a sequence of integers without sorting
问题描述
我有一个包含一长串整数的文件:
I have a file with a long list of integers:
10
4
66
....
我想使用 UNIX 命令行工具找到最大值.我知道我可以使用 sort
(并且确实有使用 sort
的 SO 上的这个问题的解决方案),但效率低下,需要 O(N*log(N))和充足的内存.通过一个简单的 for 循环,我应该能够在 O(N) 和几个字节的内存中找到最大值.
I want to find the maximum value using UNIX command line tools. I know I can use sort
(and indeed there are solutions to this problem on SO that use sort
), but that's inefficient, requiring O(N*log(N)) and plenty of memory. With a simple for loop, I should be able to find the maximum value in O(N) and a couple of bytes of memory.
似乎必须有一些程序(名称类似于 max
)可以开箱即用——这是真的吗?
It seems there must be some program out there (with a name like max
) that does this out of the box---is that true?
推荐答案
如果没有负数,你可以使用这个:
You can use this if no negative number is expected:
awk '$0>x{x=$0};END{print x}' input.txt
用它来支持负数:
awk 'BEGIN{x=-2147483648};$0>x{x=$0};END{print x}' input.txt
初始化 x
允许该解决方案正确处理值 <= 0 的整数列表.有关详细信息,请参阅注释.
Initializing x
allows the solution to properly handle integer lists with values <= 0. See the comments for more details.
这篇关于Shell 脚本:在不排序的整数序列中查找最大值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!