Implement the Selection Sort Algorithm - Test # 6

Tell us what’s happening:

Test # 6 failing.

I thought the test means that I have to assign the value of the unsorted element (currently selected) to the index of the lowest number in the unsorted part of the list first. I tried that and its reverse but it still didn’t pass.

I thought maybe the min() function is causing some problem so I rewrote the function to avoid using min() but it still didn’t work. All the other tests pass. I don’t know what is wrong. Can someone explain what might be wrong with my code please? TY

Your code so far

'''def selection_sort(array: list) -> list:

    for index, value in enumerate(array):
        least_index = array[index : len(array)].index(min(array[index : len(array)])) + index
        
        array[least_index], array[index] = array[index], array[least_index]

    return array'''

def selection_sort(array: list) -> list:
    for selection_index, selection in enumerate(array):
        minimum_index = selection_index
        minimum_value = selection

        for index in range(selection_index, len(array)):
            if array[index] < minimum_value:
                minimum_index = index
                minimum_value = array[index]
        
        array[minimum_index], array[selection_index] = array[selection_index], array[minimum_index]
        
    return array

print(selection_sort([1, 4, 2, 8, 345, 123, 43, 32, 5643, 63, 123, 43, 2, 55, 1, 234, 92]))

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/143.0.0.0 Safari/537.36

Challenge Information:

Implement the Selection Sort Algorithm - Implement the Selection Sort Algorithm

The tests only want you to do this swap if it is actually a swap (ie don’t swap an element with itself)

1 Like

I solved it with your help, thank you!

I indented the line into the if block so it swaps every time it finds an element lesser than the current selected element making sure it is an actual swap which should prevent it from swapping with itself which I think is happening every time the first element is already the least value in the array. I thought the test meant I have to swap them in a specific order.

I appreciate your help :love_you_gesture::grinning_face_with_smiling_eyes: