👤
Home Man
Search
Today's Posts
Register

BSD, Linux, and UNIX shell scripting — Post awk, bash, csh, ksh, perl, php, python, sed, sh, shell scripts, and other shell scripting languages questions here.

Finding Max value from an array

👤 Login to reply

 
Thread Tools Search this Thread
# 1  
Old 07-31-2009
Finding Max value from an array

Hi,

I need to find max and second max element from an array.
array contains 0338,0337,0339,0340,0401,0402,0403
# 2  
Old 07-31-2009
Post what you had tried so far.
# 3  
Old 07-31-2009
typeset currel_max=0

for i in `echo ${array[*]}`
do
if [ $currel_max -lt $i ]
then
currel_max=$i
fi
done

so was succesful in finding max value. but want to find second max value.

Also want to know if there is any other way to find.. instead of using for loop.
# 4  
Old 07-31-2009
Thanks for posting what you have tried

One more variable and keep flipping - but not efficient

Code:
awk 'BEGIN{ max = -1; second_max = -1 }{ if ( $0 > max ) { second_max = max; max = $0 } }END{ print second_max }' file

# 5  
Old 07-31-2009
As an alternative:

Code:
set -A MyArray 0338,0337,0339,0340,0401,0402,0403
echo ${MyArray[@]} | awk -v RS="," '1' | sort -r | head -2

0403
0402

# 6  
Old 07-31-2009
use sort -nr
'n' will take care to sort it numerically
# 7  
Old 07-31-2009
Leading 0's will take care of that...
👤 Login to reply

« Previous Thread | Next Thread »
Thread Tools Search this Thread
Search this Thread:

Advanced Search
Display Modes

More UNIX and Linux Forum Topics You Might Find Helpful
Thread Thread Starter Forum Replies Last Post
Php number array from max, min, step size mysql data barrydocks Programming 6 11-18-2014 11:23 PM
Finding max of a column grouping by the time satishrao Shell Programming and Scripting 3 03-18-2014 01:45 AM
awk, max value, array, row yifangt Shell Programming and Scripting 1 07-16-2012 02:59 PM
Finding max number in filename and opening it rpd25 Shell Programming and Scripting 8 12-28-2011 03:25 AM
finding max size Diya123 Shell Programming and Scripting 9 09-14-2011 10:25 PM
max limit in in setting array gomathi HP-UX 2 05-07-2010 10:38 AM
Max amount of awk array indices timj123 Shell Programming and Scripting 0 06-19-2008 06:51 PM
Help in finding the max and min position ahjiefreak Shell Programming and Scripting 1 06-08-2008 07:32 AM
MAX SIZE ARRAY Can Hold it epall UNIX for Advanced & Expert Users 3 06-07-2006 05:05 AM
Finding max value Enigma23 Shell Programming and Scripting 1 04-10-2005 08:34 AM


All times are GMT -4. The time now is 12:37 AM.

Unix & Linux Forums Content Copyright©1993-2018. All Rights Reserved.
×
UNIX.COM Login
Username:
Password:  
Show Password