G
G
german_mel2021-11-24 19:31:16
Python
german_mel, 2021-11-24 19:31:16

Why doesn't selection sort work?

I need to sort by list selection, I wrote the following code:

a = [78, -32, 5, 39, 58, -5, -63, 57, 72, 9,
      53, -1, 63, -97, -21, -94, -47, 57, -8, 60, 
     -23, -72, -22, -79, 90, 96, -41, -71, -48, 84,
     89, -96, 41, -16, 94, -60, -64, -39, 60, -14,
     -62, -19, -3, 32, 98, 14, 43, 3, -56, 71, 
     -71, -67, 80, 27, 92, 92, -64, 0, -77, 2,
     -26, 41, 3, -31, 48, 39, 20, -30, 35, 32,
     -58, 2, 63, 64, 66, 62, 82, -62, 9, -52,
     35, -61, 87, 78, 93, -42, 87, -72, -10, -36, 
     61, -16, 59, 59, 22, -24, -67, 76, -94, 59]

n = len(a)
for i in range(n):
    x = a.index(min(a[i:]))
    a[i], a[x] = a[x], a[i]
    
print(a)

But for some reason, when i is equal to 3, it finds the minimum element with index 2, although I kind of indicate that we are looking for the minimum in the slice from i (i.e. from 3 in this iteration), I was told what to fix to
x = a.index(min(a[i:]), i).

And so it really works fine, but I can’t understand why the first option didn’t work correctly, can someone explain it as clearly as possible?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question