the for loop index should take care of this.
For example:
Define a list LIST := { 9, 3, 0, 1}
index := 0 // this is where we start
smallestValueIndex; // keep track of value by index
for( starting at index, loop while index < LIST.length, increment index by one ) {
smallestValueIndex = index;
for( index + 1 ( let's call it j ), loop while j < LIST.length, increment j by one ) {
if( LIST[ j ] is less than LIST[ smallestValueIndex ] then
smallestValueIndex = j;
else
do nothing
}
swap( index, smallestValueIndex );
}
The first time through we have
LIST = { 9, 3, 0, 1 }
smallestValueIndex = 0;
index = 0;
j = 1; // remember j starts off as index + 1, but then changes in the inner-for loop
So we'll do our first test
if( LIST[ j ] is less than LIST[ smallestValueIndex ]
or ( substituting numbers in )
if ( list[ 1 ] is less than LIST[ 0 ] )
or ( substituting in correct values )
if ( 3 is less than 9 )
Now ask yourself, is 3 < 9 ??? I hope so.
So set smallestValueIndex equal to 1 ( which is j ) now.
so we'll increment j of the inner-for loop. We now have:
LIST = { 9, 3, 0, 1 }
smallestValueIndex = 1;
index = 0;
j = 2; // remember j starts off as index + 1, but then changes in the inner-for loop
We'll do the same test again, but with a different index.
is LIST[2] < LIST[ 1 ] ???
or
is 0 < 3 ?? I hope so, so we'll set smallestValueIndex to j, which is 2
again...
LIST = { 9, 3, 0, 1 }
smallestValueIndex = 2;
index = 0;
j = 3; // remember j starts off as index + 1, but then changes in the inner-for loop
again...
is LIST[J] < list[ smallestValueIndex ] ?
or
is 1 < 0??? I hope not!
so don't set smallestValueIndex to anything different, leave it alone.
Now we have
LIST = { 9, 3, 0, 1 }
smallestValueIndex = 2;
index = 0;
j = 4; // remember j starts off as index + 1, but then changes in the inner-for loop
j == 4 means that the inner loop will terminate because it doesn't pass it's conditional test
which leaves us at:
swap( index, smallestValueIndex );
which just means, swap the value at index, with the value at smallestValueIndex
or
swap ( 0, 2 ).
this should leave us with:
LIST = { 0, 3, 9, 1 }
smallestValueIndex = 1;
index = 1;
j = 2; // remember j starts off as index + 1, but then changes in the inner-for loop
Notice 0 and 9 were swapped
index was increased by one
smallestValueIndex is now index (again)
j = 2 which is index + 1 ( again )
By index increasing after the inner-for loop terminates, it causes the algorithm to never check anything before index. ( anything before index is already sorted )