Welcome all! In this tutorial, we are going to be looking at how you can implement the selection sort in Python!
Theory
How does the selection sorting algorithm work? Well it sorts data by finding the smallest item and swapping it into the array in the first unsorted location.
 It enumerates the array from the first unsorted element to the end
 Identifies the smallest item
 Swaps the smallest item with the first unsorted item
The selection sorting algorithm typically performs better than the bubble sort and typically worse than the insertion sorting algorithm.
Implementation
Let’s take a look at how we would implement this. We’ll start by defining a selection_sort
function which will take in an array.


We can then set up a for loop which will iterate over all of the elements in our array. Our position
will represent the location of the first unsorted element in our array.
We can then set our minimum_item to our current position:


Once we have done this, we’ll want to iterate through the rest of our array and find the smallest item in our unsorted array. If we find an element that is smaller, we’ll want to swap it to the first unsorted element in our array:


Testing it Out
Let’s have a go at running this:


As you can see, it returns a list that has been successfully sorted using the selection sort algorithm.
Conclusion
So, that’s all we are going to cover in this tutorial! We’ve successfully managed to implement the selection sorting algorithm.
If you found this useful, or have any feedback/comments then I’d love to hear them down below!