w3resource

Python: Selection sort

Python Search and Sorting : Exercise-5 with Solution

Write a Python program to sort a list of elements using the selection sort algorithm.
Note : The selection sort improves on the bubble sort by making only one exchange for every pass through the list.

Pictorial Presentation : Selection Sort

Python: Selection Sort

Sample Solution:

Python Code:

def selectionSort(nlist):
   for fillslot in range(len(nlist)-1,0,-1):
       maxpos=0
       for location in range(1,fillslot+1):
           if nlist[location]>nlist[maxpos]:
               maxpos = location

       temp = nlist[fillslot]
       nlist[fillslot] = nlist[maxpos]
       nlist[maxpos] = temp

nlist = [14,46,43,27,57,41,45,21,70]
selectionSort(nlist)
print(nlist)

Sample Output:

[14, 21, 27, 41, 43, 45, 46, 57, 70]

Flowchart:

Flowchart: Python Data Structures and Algorithms: Selection sort

Python Code Editor :

Contribute your code and comments through Disqus.

Previous: Write a Python program to sort a list of elements using the bubble sort algorithm.
Next: Write a Python program to sort a list of elements using the insertion sort algorithm.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://198.211.115.131/python-exercises/data-structures-and-algorithms/python-search-and-sorting-exercise-5.php