# SORT ELEMENTS OF AN ARRAY IN LINUX

In this Blog, sharing code to sort the elements of an array in ascending and descending order as well.
ASCENDING ORDER

arr=(4 3 2 1) ## Array of 4 Elements
len=\${#arr[@]} ## It gives the length of an Array arr
k=0
lngthminusone=\$(( \$len – 1))
while [ \$k -lt \$len ] ##Outer Loop which will run len-1 times where len is length of Array
do
i=0 ## This variable set to 0 every time inner loop starts
while [ \$i -lt \$lngthminusone ] ## Inner loop which will arrange an element of an array in ascending order. Outer Loop make sure , it will do this activity for all elements
do j=\$(( \$i + 1))
if [ \${arr[i]} -gt \${arr[j]} ]
then
temp=\${arr[i]}
arr[i]=\${arr[j]}
arr[j]=\$temp
echo “Value of i is ” \${arr[i]} ##Echo commands used for debugging purpose only.
echo “value of j is ” \${arr[j]}
echo \${arr[*]}
fi
i=\$(( \$i + 1))
done
k=\$(( \$k + 1))
done
echo \${arr[*]}

DESCENDING ORDER

arr=(1 3 5 2) ## Array of 4 Elements
len=\${#arr[@]} ## It gives the length of an Array arr
k=0
lngthminusone=\$(( \$len – 1))
while [ \$k -lt \$len ] ##Outer Loop which will run len-1 times where len is length of Array
do
i=0 ## This variable set to 0 every time inner loop starts
while [ \$i -lt \$lngthminusone ] ## Inner loop which will arrange an element of an array in descending order. Outer Loop make sure , it will do this activity for all elements
do j=\$(( \$i + 1))
if [ \${arr[i]} -lt \${arr[j]} ]
then
temp=\${arr[i]}
arr[i]=\${arr[j]}
arr[j]=\$temp
echo “Value of i is ” \${arr[i]} ##Echo commands used for debugging purpose only.
echo “value of j is ” \${arr[j]}
echo \${arr[*]}
fi
i=\$(( \$i + 1))
done
k=\$(( \$k + 1))
done
echo \${arr[*]}