Selection sort Python Program

The selection sort method arrange a list by repeatedly finding the minimum element from the unsorted list and putting it at the beginning. The algorithm maintains two sub-lists in a given list

1) The sublist which is already sorted.
2) Remaining sublist which is unsorted.

In every iteration of selection sort, the minimum element from the unsorted sublist is picked and moved to the sorted sublist.

In the first iteration, the whole list is unsorted so our method finds out the minimum element from the list and swap this element with the element at first position.

Now we have two lists 1.  one that is sorted and contains only one element  2. All the remaining element with unsorted element.

The second iteration will try to find out the minimum element from this second unsorted element and that element will be swapped with the second position element.

This process will continue until second list is empty. Here is the working model of the selection sort program implemented in Python.

Source code of Selection sort Python Program

x =[3,56,2,56,78,56,34,23,4,78,8,123,45]
for i in range(0,12):
    pos = i 
    low = x[pos]
    for j in range(i+1,13):
            pos = j
            low = x[j]
    x[i],x[pos] = x[pos],x[i]

print("Sorted Array :")            

The above selection sort algorithm is able to sort only a list of 13 integer type element. if you exceed the size of list element, the above program will generate a runtime error. So you can modify the above like like this.

#  python program to arrange a list of integer element in ascending order
#  made by              : rakesh kumar
#  last revision        : 18/09/2019

x = [3, 56, 2, 56, 78, 56, 34, 23, 4, 78, 8, 123, 45]
n = len(x)
for i in range(0, n-1):   # this loop is for step
    pos = i
    low = x[pos]
    for j in range(i+1, n):
        if(low > x[j]):
            pos = j
            low = x[j]
    x[i], x[pos] = x[pos], x[i]

print("Sorted Array :")

The output of selection sort Python Program

rakesh@folio MINGW64 /e/python (master)
$ C:/Python37/python.exe e:/python/DataStructure/
Sorted Array :
[2, 3, 4, 8, 23, 34, 45, 56, 56, 56, 78, 78, 123]

Extra Programming Challenge:  The above selection sort algorithm arranges given list in ascending order. You are requested to design this program in this way so that it can arrange a list in descending order of any size.

Print Friendly, PDF & Email

Related Posts

If you like CBSEToaday and would like to contribute, you can also write an article using submit article or mail your article to See your article appearing on the main page and help other students/teachers.