TWO ARRAYS ARE EQUAL OR NOT

In this blog, sharing code to check whether two arrays are equal or not . Below is the code explanation in 4 steps.

1. Check the length of each Array, if length is same , then we can compare , else exit.
2. If length is same for both the Arrays, then arrange them in either ascending or descending order.
3. Once arrays are sorted in an order, then compare element of each Array one by one and if elements are same, increment a dummy counter.
4. If the value of counter is same as length of any array , then Arrays are considered to be equal.

NOTE : Code to arrange the Array is written twice , one for each Array. You can create function and Pass Array as an argument and use it .

arr=(4 3 2 1) ## First Array of 4 elements
arr_2=(1 4 2 3) ## Second Array of 4 elements
len_arr=${#arr[@]} ## Length of Array Arr.
len_arr_2=${#arr_2[@]} ## Length of Array Arr_2.


if [ $len_arr -eq $len_arr_2 ]
then
k=0
lngthminusone=$(( $len_arr - 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 everytime inner loop starts
while [ $i -lt $lngthminusone ] ## Inner loop which will arrange an element of an array in ascending order.Outer Loop makes 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
fi
i=$(( $i + 1))
done
k=$(( $k + 1))
done
k=0
lngthminusone=$(( $len_arr_2 - 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 everytime inner loop starts
while [ $i -lt $lngthminusone ] ## Inner loop which will arrange an element of an array in ascending order.Outer Loop makes sure , it will do this activity for all elements
do j=$(( $i + 1))
if [ ${arr_2[i]} -gt ${arr_2[j]} ]
then
temp=${arr_2[i]}
arr_2[i]=${arr_2[j]}
arr_2[j]=$temp
fi
i=$(( $i + 1))
done
k=$(( $k + 1))
done
echo ${arr[*]}
echo ${arr_2[*]}

i=0
counter=0 ## setting counter to 0
while [ $i -lt $len_arr ]
do
if [ ${arr[i]} -eq ${arr_2[i]} ]
then
counter=$(( $counter + 1)) ## Incrementing the counter
fi
i=$(( $i + 1))
done
if [ $counter -eq $len_arr ]
then
echo " Arrays are equal"
fi
if [ $counter -ne $len_arr ]
then
echo " Arrays are not equal"
fi
fi


if [ $len_arr -ne $len_arr_2 ]
then
echo "Length of both Array is not same and hence not equal as well"
fi

Related posts