0

I have implemented the selection sort in python, but couldn't understand this tiny part of inner for loop.

The for loop for j, I have the range from outer index i to max length-1, this makes a lot of sense to me, but the result wouldn't count the last number in the array, and I can't think of the reason.

However, If I change the range from i to max length, it would work. (which in my knowledge should be exceeding the array since alist[len(alist)] would count 1 digit pass the max number).

#Go over the loop, find the smallest num
def swap(arr, num_1, num_2):
    temp = arr[num_1]
    arr[num_1] = arr[num_2]
    arr[num_2] = temp

def selectionSort(alist):
    for i in range(0, len(alist)-1):
        min = i
        # for j in range(i+1, len(alist)):
        # Why len(alist)-1 doesn't work?
        for j in range(i, len(alist)-1):
            if alist[j] < alist[min]:
                min = j
        if min != i :
            swap(alist,i,min)
    return alist


# Test
print "-------------Test--- ----------"
A = [2,1,9,3,4,100,99,30]
print selectionSort(A)

1 Answer 1

2

Read about ranges in Python again; you don't have a clear concept of them. range(0, 3), for example, is roughly equivalent to [0, 1, 2]. It stops just short of the second value. The same is true of slices.

Sign up to request clarification or add additional context in comments.

5 Comments

I read over it, and it makes sense now! However if this is the case, say I want to traverse through this array A in the test case, to interate through them all in the outer loop, can I just have "for i in range(0, len(alist))" ? since len(alist) is 8, and it will only loop to A[7]
Well, that would work, because of the way your program is set up. But if I were writing a selection sort, I'd stop the outer loop at the next-to-last item, and start j at i+1. Note, also, that starting at zero is the default, so you can just say for i in range(len(alist)).
Would you mind elaborate on your thought? I was looking at someone's implementation on selection sort, it implements exactly as how you described it. If say, you stop the outer loop @ next-to-last item, wouldn't you then ignore the last item in the array?also to start j at i+1, does that mean so you want to exclude the case where j'th item compares to itself?
There's no point in comparing a number to itself; it's always equal. As for the last item, we keep swapping lower-valued items upward, so the last item will always be the highest-valued item; if it were not, it would have been swapped upward at some point.
It makes sense now!! Thank you

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.