w3resource

Python: Selection sort


5. Selection Sort

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

For more Practice: Solve these Related Problems:

  • Write a Python program to implement selection sort and print the index of each minimum element as it is selected.
  • Write a Python script to sort a list using selection sort and count the number of comparisons made.
  • Write a Python program to modify selection sort to sort a list of tuples based on the second element of each tuple.
  • Write a Python function to perform selection sort and output the partially sorted list after every complete pass.

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.



Follow us on Facebook and Twitter for latest update.