Python Selection Sort Wrong Answer

Two changes will get the code working correctly:

  • In the inner loop, start at the outer loop index
  • When swapping values, store the index in a variable first

Try this code:

def SelectionSortD(li):
    for i in range(len(li)):
        minm = li[i]
        for k in li[i:]:  # start at outer index
            if k < minm:
                minm = k
        x = li.index(minm)  # store index first
        li[i],li[x] = li[x],li[i]
    return li
    
li = [int(h) for h in input().split()]
x = SelectionSortD(li)
print(x)

Output

3 4 2 8 5 7 6
[2, 3, 4, 5, 6, 7, 8]

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top