Jun-02-2020, 09:44 PM
import numpy as np
def selection_sort(x):
for i in range(len(x)):
swap = i + np.argmin(x[i:])
(x[i], x[swap]) = (x[swap], x[i])
return x
x = np.array([2, 1, 4, 3, 5])
selection_sort(x)A line that calculates swap index is something that I don't understand. Let's say that we're on i=1. After i=0 the array order is (1,2,4,3,5) and now swap = 1+1(because 2 is the smallest element of array and it has index 1) which means that swap = 2. Now next line swaps places so instead of x[1] (which is 2) we have x[2] which is 4. That gives an incorrect order (1,4). And what happens when i=4 is that swap becomes a larger index number than the number of elements in array. I ran this code in editor and it gives the correct outcome which means that my reasoning from previous paragraph is wrong. What did I get wrong? I would appreciate that someone explains to me how this works.
