I am currently learning some bash in my free time and worked on a few easy coding challenges using bash for fun. Solving the last challenge I observed some weird optimization issues:
# read the number of input values
read N
# read all input values into an array
readarray -n $N P
# sort the input array in an ascending order
PS=($(printf "%s\n" ${P[@]} | sort -n))
# init the current minimum distance of two horses by the max input value plus one
Min=10000001
# iterate over the ascending sorted array
# and find the minimum distance
for ((i = 1; i < N; i++)); do
# compute the difference between the current and the last
#D=$((PS[i]-PS[i-1]))
D=$((-PS[i-1]+PS[i]))
if [ $D -le $Min ]; then
Min=$D
fi
done
# finally print the minimum distnce
echo $Min
Somehow accessing PS[i] and right afterwards PS[i-1] results in the test case of a 100'000 input values to run out of time. Accessing the exact same array elements in the reversed order however results the test case to run through properly. A no- associative array access should take O(1) time, so how is it possible that the order of access can effect the runtime performance? Is there some bash magic going on internally I am not aware of (like arrays being implemented as singly linked lists or something like that??)