for iteration in range(len(list) - 1):
index = iteration +1 #This is the line which has no effect on the inner loop
for index in range(len(list)):
if list[iteration] > list[index]:
newmin = list[index]
newminindex = index
if iteration != newminindex :
swapnumbers(list,iteration, newminindex)
The above is a code snippet I wrote for selection sort algorithm. However I see the inner loop start counter always starting from 0. Request for expert comment.
You really should be using
enumerate
for stuff like this, as you can loop through the index and the value at the same time (which will save you the hassle of using two for-loops).Your inner loop is overriding the variable
index
that you defined in the first loop.The
for index in range(len(list))
loop executes the loop body withindex
first set to0
, then1
, then2
, etc. up tolen(list) - 1
. The previous value ofindex
is ignored and overwritten. If you wantindex
to start atiteration + 1
, use the 2-argument form ofrange
:Try this instead:
index
is being reassigned anyway within thefor
-loop soindex = iteration + 1
is not having any effect.