This is a Python program to implement selection sort.
The program sorts a list by selection sort.
1. Create a function selection_sort that takes a list as argument.
2. Inside the function create a loop with a loop variable i that counts from 0 to the length of the list – 1.
3. Create a variable smallest with initial value i.
4. Create an inner loop with a loop variable j that counts from i + 1 up to the length of the list – 1.
5. Inside the inner loop, if the elements at index j is smaller than the element at index smallest, then set smallest equal to j.
6. After the inner loop finishes, swap the elements at indexes i and smallest.
Here is the source code of a Python program to implement selection sort. The program output is shown below.
def selection_sort(alist): for i in range(0, len(alist) - 1): smallest = i for j in range(i + 1, len(alist)): if alist[j] < alist[smallest]: smallest = j alist[i], alist[smallest] = alist[smallest], alist[i] alist = input('Enter the list of numbers: ').split() alist = [int(x) for x in alist] selection_sort(alist) print('Sorted list: ', end='') print(alist)
1. The user is prompted to enter a list of numbers.
2. The list is passed to the selection_sort function.
3. The sorted list is displayed.
Case 1: Enter the list of numbers: 3 1 4 5 2 6 Sorted list: [1, 2, 3, 4, 5, 6] Case 2: Enter the list of numbers: 2 10 5 38 1 7 Sorted list: [1, 2, 5, 7, 10, 38] Case 3: Enter the list of numbers: 5 3 2 1 0 Sorted list: [0, 1, 2, 3, 5]
Sanfoundry Global Education & Learning Series – Python Programs.
To practice all Python programs, here is complete set of 150+ Python Problems and Solutions.
- Get Free Certificate of Merit in Python Programming
- Participate in Python Programming Certification Contest
- Become a Top Ranker in Python Programming
- Take Python Programming Tests
- Chapterwise Practice Tests: Chapter 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
- Chapterwise Mock Tests: Chapter 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
- Apply for Programming Internship
- Practice Programming MCQs
- Buy Information Technology Books
- Apply for Python Internship
- Buy Python Books