Implement the Selection Sort Algorithm - Implement the Selection Sort Algorithm

Tell us what’s happening:

I have managed to make an algorithm that sorts through all of the numbers however, since it technically iterates over each element, it’s being counted as unnecessary swapping so I can’t get past test case #6.

Your code so far

def selection_sort(num_list):
    for i in range(len(num_list)):
        for j in range(len(num_list) - 1):
            if num_list[j] > num_list[j + 1]:
                temp = num_list[j]
                num_list[j] = num_list[j + 1]
                num_list[j + 1] = temp
                
    return num_list

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:150.0) Gecko/20100101 Firefox/150.0

Challenge Information:

Implement the Selection Sort Algorithm - Implement the Selection Sort Algorithm

Well, that’s not selection sort really, it looks a bit like bubble sort. Take another look at the instructions, selection sort is explained there.

I tried the way described but I can’t figure out how to swap values without iterating through the whole list

Here’s something that’s closer to what’s asked but it still doesn’t pass case 6

def selection_sort(num_list):
    for i in range(len(num_list)):
        temp = num_list[i]
        swap = num_list[i]
        for j in range(i + 1, len(num_list)):
            if temp >= num_list[j]:
                swap_index = j
                temp = num_list[j]

        num_list[i] = temp

        if swap_index == 0:
            pass
        elif i < len(num_list):
            num_list[swap_index] = swap
            swap_index = 0
        else:
            swap_index = i 
            num_list[swap_index] = swap
    
    return num_list

You are not far right now.

Notice though that every time to num_list[i] is written temp, even if that’s already the smallest number in the unsorted part of list.

Thanks for the help,
all that was messing me up for hours was a single line :melting_face:

is buble sort and selection sort the same?