zig-zag arrangement in Array

Consider an array a= (1 4 3 -1 10 6) of length N, so zig-zag arrangement of elements is
arr[0] < arr[1]  > arr[2] < arr[3] > arr[4] < . . . . arr[n-2] < arr[n-1] > arr[n]

Here, first we need to run code which will sort the data in descending order .For this you can refer to this blog. Once you arranged the data in descending order, then use the below code to bring elements in zig-zag order.

i=0
DescArr=(10 6 4 3 1 -1) ## Array in desc order.
len1=${#DescArr[@]}
LenMinusOne=$(( $len1 - 1))
while [ $i -lt $LenMinusOne ]
do
j=$(( $i + 1))
if [ $(( $i % 2 )) -eq 0 ] ## only changing positions of alternate elements
then
if [ ${DescArr[i]} -gt ${DescArr[j]} ]
then
temp=${DescArr[i]}
DescArr[i]=${DescArr[j]}
DescArr[j]=$temp
fi
fi
i=$(( $i + 1))
done



Related posts