Python Program for Selection Sort
Intermediate · Searching and sorting
Selection sort sorts a list by repeatedly finding the smallest number in the unsorted part and moving it to the front. After the first pass the smallest number is in place, after the second pass the two smallest are, and so on. This program prints the list after each pass.
Program
Original list: [29, 10, 14, 37, 13] After pass 1 (placed 10): [10, 29, 14, 37, 13] After pass 2 (placed 13): [10, 13, 14, 37, 29] After pass 3 (placed 14): [10, 13, 14, 37, 29] After pass 4 (placed 29): [10, 13, 14, 29, 37] Sorted list: [10, 13, 14, 29, 37]
How it works
- In pass
i, everything before indexiis already sorted and the rest still needs sorting. - The inner loop scans the unsorted part and remembers the position of the smallest number in
min_index. - One swap then moves that smallest number into position
i. - Pass 3 changes nothing because 14 is already in the right place, but selection sort still has to check.
- Selection sort makes at most n - 1 swaps, fewer than bubble sort, but it still needs about n x n comparisons.
Another way to write it
Using min() and a new list
Sorted so far: [10] Sorted so far: [10, 13] Sorted so far: [10, 13, 14] Sorted so far: [10, 13, 14, 29] Sorted so far: [10, 13, 14, 29, 37] Sorted list: [10, 13, 14, 29, 37]
The same idea written with built-in functions: pick the smallest, move it to a new list, repeat. It is shorter but uses a second list.
Try it yourself
Change the program to find the largest number in each pass, so the list is sorted in descending order.
Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.
Related programs
All Python programs · CBSE class 12 practical file · Python exercises