Selection Sort using Python

Selection Sort using Python

<- Go Back to Index

What is Selection Sort?

The selection sort algorithm sorts an array by continuously finding the minimum element from the unsorted part and putting it at the beginning.

We can understand this with an example ->

  • Consider the below list of elements

image.png

  • Next thing you try to do is to find a candidate for the first position, that element will be the lowest element in the list considering that we are ascending.

image.png

  • Then we move towards the next element and find the best element for the second position. Which will be the second minimum element in the list.

image.png

  • Then we move on to the next element, if we keep on repeating this process we will finally have a sorted array list.

Let's Implement this

  • First, we create a function and apply the logic in that, for this we will need 2 loops the outer loop will increment each element by one and ignore them once it's sorted also the inner loop will compare the elements with the outer loop.
def selection_sort(mylist):
    for i in range(len(mylist)):
        for j in range(i+1,len(mylist)):
            if mylist[i]>mylist[j]:
                mylist[i],mylist[j] = mylist[j],mylist[i]
    return mylist
  • Now finally define the main function
if __name__ == '__main__':
    mylist = [78,65,90,54,65,21,43]
    print(selection_sort(mylist))
  • Let's now combine all in one single code
def selection_sort(mylist):
    for i in range(len(mylist)):
        for j in range(i+1,len(mylist)):
            if mylist[i]>mylist[j]:
                mylist[i],mylist[j] = mylist[j],mylist[i]

    return mylist
if __name__ == '__main__':
    mylist = [78,65,90,54,65,21,43]
    print(selection_sort(mylist))

Thank-you!

I am glad you made it to the end of this article. I hope you got to learn something, if so please leave a Like which will encourage me for my upcoming write-ups.