Editor

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

selection_sort.py
numbers = [29, 10, 14, 37, 13]
print("Original list:", numbers)
n = len(numbers)
for i in range(n - 1):
# Find the smallest number in the unsorted part, from index i onwards
min_index = i
for j in range(i + 1, n):
if numbers[j] < numbers[min_index]:
min_index = j
# Swap it into position i
numbers[i], numbers[min_index] = numbers[min_index], numbers[i]
print(f"After pass {i + 1} (placed {numbers[i]}):", numbers)
print("Sorted list:", numbers)
Output
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

  1. In pass i, everything before index i is already sorted and the rest still needs sorting.
  2. The inner loop scans the unsorted part and remembers the position of the smallest number in min_index.
  3. One swap then moves that smallest number into position i.
  4. Pass 3 changes nothing because 14 is already in the right place, but selection sort still has to check.
  5. 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

Using min() and a new list
numbers = [29, 10, 14, 37, 13]
remaining = numbers.copy()
sorted_list = []
while remaining:
smallest = min(remaining) # select the smallest
remaining.remove(smallest)
sorted_list.append(smallest)
print("Sorted so far:", sorted_list)
print("Sorted list:", sorted_list)
Output
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.

All Python programs · CBSE class 12 practical file · Python exercises