Python Selection Sort Program

Python – Selection Sort

In this tutorial, we will implement Selection Sort Algorithm in Python.

We will write a function selection_sort() with a list as parameter. Also, by default, the selection_sort() function sorts the list in ascending order. To get the descending order, all you have to do is just reverse the list.

Python Program

def selection_sort(nlist):
    for i in range(0, len(nlist) - 1):
        smallest = i
        for j in range(i + 1, len(nlist)):
            if nlist[j] < nlist[smallest]:
                smallest = j
        nlist[i], nlist[smallest] = nlist[smallest], nlist[i]

# Input list
alist = [1, 74, 96, 5, 42, 63]
print('Input List\n', alist)

# Sort list
selection_sort(alist)
print('Sorted List\n', alist)
Run Code Copy

Output

Input List
 [1, 74, 96, 5, 42, 63]
Sorted List
 [1, 5, 42, 63, 74, 96]

Conclusion

In this tutorial of Python Examples, we learned how to implement Selection Sort algorithm in Python.

Code copied to clipboard successfully 👍