Implementation of the Selection Sort Algorithm I have tried to implement the Selection Sort Algorithm in two different ways, and I was just wondering if that is considered to be a valid implementation of that algorithm. Would that be also considered an efficient implementation of the algorithm, or are there different and more efficient ways?

Here are my implementations:

Implementation Attempt #1

def selection_sort(L: List[int]) -&gt; List[int]:
    for i in range(len(L) - 1):
        j = i
        smallest_num = L[i]
        while j &lt; len(L) - 1:
            if smallest_num &gt; L[j + 1]:
                smallest_num = L[j + 1]
            j += 1
        L[L.index(smallest_num)], L[i] = L[i], L[L.index(smallest_num)]
    return L


Implementation Attempt #2

def selection_sort(L: List[int]):
    for i in range(len(L) - 1):
        j = i
        while j &lt; len(L) - 1:
            swap_min(L, i)
            j += 1
    return L

def swap_min(L: List[int], n: int) -&gt; None:
    smallet_num = min(L[n:])
    sm_indx = L.index(smallet_num)
    L[n], L[sm_indx] = L[sm_indx], L[n]
The use of L.index(smallest_num) makes neither of these implementations valid. Using the input list [1, 0, 1, 0, 1] as an example, both of your implementations give [1, 1, 0, 0, 1] as their result, and this is clearly not sorted correctly.

The reason your algorithm doesn't work on this input is that it contains duplicate elements, so the .index method doesn't always return the index you want it to; as the documentation says, the .index method returns the index of the first occurrence of the given value. That will not always be the index of the occurrence you want to find; sometimes, that index is in the "already-sorted" part of the list, so you end up swapping things back there where they don't belong.

A correct implementation of selection sort should search for the index of the minimum element in just the unsorted part of the list.