Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
selection sort
#1
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.
Reply
#2
(Jun-02-2020, 09:44 PM)Truman Wrote: now swap = 1+1(because 2 is the smallest element of array and it has index 1)
no, it's swap = 1 + 0, because 2 is the smallest value, with index 0 in [2, 4, 3, 5] (x[i:])
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#3
Correct. I missed that!
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020