SPOILERS - Selection Sort Algorithm - Viable Solution?

SPOILERS - this post contains a potential solution for the Implement the Selection Sort Algorithm exercise in the Python curriculum.

I found a way to implement selection sort that is different from what I saw in the forums after completing it, and doesn’t match the common solutions you can find in keyword searches online. I wondered if I could get some feedback. Is this a viable solution? Is it efficient enough to be worth using?

def selection_sort(numbers):
    index = 0
    length = len(numbers)
    while index < length:
        small = min(numbers[index:length])
        index_small = numbers.index(small, index)
        if index == index_small:
            index += 1    
        else:
            numbers[index], numbers[index_small] = numbers[index_small], numbers[index]
            index += 1
    return numbers

Thank you!

Hi @daimothra ,

We have blurred this solution (with [spoiler][/spoiler] tags) so that users who have not completed this challenge can read the discussion in this thread without giving away the solution.

We are also changing the category to “Code Feedback” to better reflect the nature of this topic.

Happy coding!

Thank you! I’ll remember to take these steps myself if I post solutions for feedback in the future.

Selection sort is not the most efficient sorting algorithm, so using it would depend on how many numbers are in the sorted list. For small lists any algorithm inefficiency would not matter that much.

There’s couple points that could be looked at:

  • Using while loop. while loop is not very convenient in usage, there’s always risk that its condition has one-off error and the incrementation of index needs to be done manually. On the other hand iterating over numbers with for loop, would remove these details.
  • Iterating over remaining numbers twice:
          small = min(numbers[index:length])
          index_small = numbers.index(small, index)
    
    It might be better to find way to get smallest number and index on which it is in single step. But again, for small lists this won’t really matter, while for large lists requiring efficient sorting, selection sort wouldn’t be used in the first place.
  • The if/else blocks contains identical line. This usually means something can be simplified further, by extracting the same parts.

This is super helpful, thank you! Brevity is not a strong suit of mine in any area so I know it’s something I need to pay extra attention to in Python lol.