Count Inversions in Array

Consider an Array (2 4 1 3 5). Inversions are those pairs where a[i]>a[j] and i<j . For above mentioned array, below are the pairs of Inversions. So, total Count Inversions are 3 for this Array.
(2 1)
(4 1)
(4 3)
Below is the code for the same using shell scripting.

a=(2 4 1 3 5)
len=${#a[@]}
lngthminusone=$(( $len -1))
i=0
## This while loop will run inner loop for each element.
while [ $i -lt $len ]
do
j=0
## This while loop will compare one element with rest of the elements.
while [ $j -lt $lngthminusone ]
do
j=$(( $j + 1))
## Checking Inversion pairs for Array.
if [[ ${a[i]} -gt ${a[j]} && $i -lt $j ]]
then
newlist=()
newlist+=${a[i]}
newlist+=${a[j]}
echo ${newlist[*]}
fi
done
i=$(( $i + 1))
done


Related posts