Consider an array (for example (1 3 2 4 6 12))of even number of elements like 2,4 or any number which is even .
Need to arrange array in below order.
First maximum First Minimum Second Max Second Min Third Max Third Min….
I have divided code into 4 parts.
## Arrange elements in Descending order and create a blank array newlist of same length with value 0##
arr=(1 3 2 4 6 12)
len=${#arr[@]}
k=0
newlist=()
lngthminusone=$(( $len -1))
echo $lngthminusone
while [ $k -lt $len ]
do
i=0
value=0
newlist+=$value
while [ $i -lt $lngthminusone ]
do
j=$(( $i + 1))
if [ ${arr[i]} -lt ${arr[j]} ]
then
temp=${arr[i]}
arr[i]=${arr[j]}
arr[j]=$temp
fi
i=$(( $i + 1))
done
k=$(( $k + 1))
done
echo ${arr[*]}
##Assign max value to first element and first minimum value to second element##
newlist[0]=${arr[0]}
newlist[1]=${arr[lngthminusone]}
##This section will assign all max values excluding first maximum which is already set in above section to even indexes like 2 4##
i=0
j=0
while [ $i -lt $len ]
do
if [[ $(( $i % 2 )) -eq "0" && $(( $i+2)) -lt $len ]]
then
newlist[i+2]=${arr[j+1]}
fi
i=$(( $i + 2))
j=$(( $j + 1))
done
echo ${newlist[*]}
##This Section will arrange all min values excluding first min which is already set in above section(2) to odd indexes like 3 5##
i=1
j=$lngthminusone
while [ $i -lt $len ]
do
if [[ $(( $i % 2 )) -ne "0" && $(( $i+2 )) -lt $len ]]
then
newlist[i+2]=${arr[j-1]}
fi
i=$(( $i + 2))
j=$(( $j - 1))
done
echo ${newlist[*]}