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

Post what you had tried so far.

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.

Thanks for posting what you have tried :b:

One more variable and keep flipping - but not efficient

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

As an alternative:

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

0403
0402

use sort -nr
'n' will take care to sort it numerically

Leading 0's will take care of that...

Thanks for the replies.

But now i have modified my script from an array to a file. Now I will have to find the Max and Second Max from a file and store them in two variables.

Also

---------- Post updated at 09:39 AM ---------- Previous update was at 09:14 AM ----------

[/COLOR]

This is failing in the case the contents of file are:
0336
0405
0337
0338

max is 0405 and second max is 0338.. but above code is returning 0336 as second max..

Here is solution for you, little fix your 1st script. No need to echo array, use it. You can test values or give the list for sort and then take so many value as you like.

#!/bin/ksh
#!/bin/bash

array=(0338 0337 0339 0340 0401 0402 0403)
for i in ${array
[*]}
do
        echo "$i"
done | sort -nr | head -2

Or you can put sorted list to the array and take so many values as you like:

# set array using array=( list of values )
# make max
max=(
$(for i in ${array
[*]}
do
        echo "$i"
done | sort -nr ) 
)
echo "1st: ${max[0]}" 
echo "2nd: ${max[1]}"
echo "3th: ${max[2]}"

---------- Post updated at 08:56 PM ---------- Previous update was at 08:32 PM ----------

Using file:

array=( $(<somefile ) )

max=(
$(for i in ${array
[*]}
do
        echo "$i"
done | sort -nr )
)
echo "1. ${max[0]}"
echo "2. ${max[1]}"

Or using sort and two first lines:

cnt=1
sort -nr somefile | while read line
do
        (( cnt  > 2 )) && break
        echo "$cnt. $line"
        (( cnt+=1))
done

Or ...

---------- Post updated at 09:00 PM ---------- Previous update was at 08:56 PM ----------

Using sort + awk

sort -nr somefile | awk 'NR <= 2 { print NR ".",$1 }'

That's a good catch :slight_smile:

awk 'BEGIN{ max = -1; second_max = -1 }{ if ( $0 > max ) { second_max = max; max = $0 } else { if ( $0 > second_max ) second_max = $0 } }END{ print second_max }' filename

Was not sure if its always going to be 4 char long