I'm a bit stuck trying to understand the following script from a book:
values=(39 5 36 12 9 3 2 30 4 18 22 1 28 25)
numvalues=${#values[@]}
for (( i=0; i < numvalues; i++ )); do
lowest=$i
for (( j=i; j < numvalues; j++ )); do
if [ ${values[j]} -le ${values[$lowest]} ]; then
lowest=$j
fi
done
temp=${values[i]}
values[i]=${values[lowest]}
values[lowest]=$temp
done
for (( i=0; i < numvalues; i++ )); do
echo -ne "${values[$i]}\t"
done
echo
The script is performing a selection sort on the numbers in the array, and is ultimately sorting them in correct numerical order. According to the book "the outer i for loop is for looping over the entire array and pointing to the current 'head' (where we put any value we need to swap). The variable lowest is set to this index." I understand this part, and I guess the value of lowest on the first iteration will be index 0, and the value 39.
What I am struggling to understand is how the inner j loop is working. The book says 'it compares the remaining elements with the value at lowest; if a value is less than lowest is set to the index of that element.'
I can't get my head around how the value of j is any different to the value of i. To my mind if j=i, which is on first iteration 0, then j is also equal to 0. I guess this must change on the second and subsequent iterations. I know that the value of j must differ from the value of i, as this is what the [ ${values[j]} -le ${values[$lowest]} part of the script is calculating.
Does this work because of the j=i and subsequent j++ part of the inner for loop? If j=i, and on the second iteration if i=1, does this mean that j++ is equal to 2?
I hope this makes some kind of sense. It's kind of tough teaching yourself from a book, so I really grateful if any of you out there can help me with this.