Vtechster
Vtechster

Reputation: 47

Python Selection Sort Wrong Answer

When I run code it gives wrong answer. What's wrong with this can someone tell?

def SelectionSortD(li):
    for i in range(len(li)-1):
        minm = float("inf")
        for k in li:
            if k < minm:
                minm = k
        li[i],li[li.index(minm)] = li[li.index(minm)],li[i]
    return li
li = [int(h) for h in input().split()]
x = SelectionSortD(li)
print(x)

For example when 3 4 2 8 5 7 6 is given as input it gives answer as [3, 4, 8, 5, 7, 2, 6]

Upvotes: 0

Views: 28

Answers (1)

Mike67
Mike67

Reputation: 11342

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]

Upvotes: 1

Related Questions