Python Selection Sort Program (with Explanation)
Selection sort divides the list into a sorted part on the left and an unsorted part on the right. On every round it "selects" the minimum of the unsorted part and moves it to the border between the two. Like bubble sort, it is mainly a teaching algorithm: for real programs use sorted().
Its one practical selling point is that it performs very few swaps, which matters only when moving data is expensive. In Python lists, a swap is cheap, so this advantage rarely applies.
| Input | A list of comparable items |
|---|---|
| Output | A new list sorted in ascending order |
| Approach | Find the minimum of the unsorted part, swap it to the front, shrink the unsorted part |
| Time complexity | O(n²) in every case; O(1) extra space; at most n − 1 swaps |
Approach: how selection sort works step by step
- Assume position
0holds the smallest value. - Scan the rest of the list; whenever you see something smaller, remember its index.
- Swap the smallest value found into position
0. - Repeat from position
1, then2, and so on. - After n − 1 rounds the last item is automatically in place.
Trace for [29, 10, 14, 37, 13]: smallest is 10, swap with 29 gives [10, 29, 14, 37, 13]; next smallest is 13, giving [10, 13, 14, 37, 29]; 14 is already in place; finally 29 and 37 swap.
How the selection sort code works
The outer for loop variable start marks the first unsorted position. The inner loop starts at start + 1 and updates smallest whenever it finds a lower value. Only after the inner loop has finished does the code swap, so each outer round does exactly one swap. See nested loops for how the two loops interact.
items = [29, 10, 14, 37, 13]
for start in range(len(items) - 1):
smallest = items.index(min(items[start:]), start)
items[start], items[smallest] = items[smallest], items[start]
print(items)Selection sort vs bubble sort vs sorted()
| Aspect | Selection sort | Bubble sort | `sorted()` |
|---|---|---|---|
| Best-case time | O(n²) | O(n) with early exit | O(n) |
| Worst-case time | O(n²) | O(n²) | O(n log n) |
| Swaps | At most n − 1 | Up to about n²/2 | Not applicable |
| Stable (keeps equal items in order)? | No (in the usual form) | Yes | Yes |
Variations: descending order and sorting by a key
For descending order, search for the largest item instead (> in the comparison). To sort records such as (name, marks) pairs, compare items[i][1] instead of items[i]. In production code, the same idea is written as sorted(students, key=lambda s: s[1]); see Python sorting.
Examples you can run
Press Run, then edit the code and run it again.
Sort a list of marks
The function returns a sorted copy and leaves the original list alone.
def selection_sort(items):
items = items[:]
for start in range(len(items) - 1):
smallest = start
for i in range(start + 1, len(items)):
if items[i] < items[smallest]:
smallest = i
items[start], items[smallest] = items[smallest], items[start]
return items
marks = [64, 25, 12, 22, 11]
print(selection_sort(marks))
print(marks)Expected output[11, 12, 22, 25, 64]
[64, 25, 12, 22, 11]
Descending order by selecting the largest item
The only change is that we track the index of the largest value.
def selection_sort_desc(items):
items = items[:]
for start in range(len(items) - 1):
largest = start
for i in range(start + 1, len(items)):
if items[i] > items[largest]:
largest = i
items[start], items[largest] = items[largest], items[start]
return items
print(selection_sort_desc([7, 2, 9, 4]))Expected output[9, 7, 4, 2]
Edge cases: duplicates, negatives and strings
Duplicates are kept; negative numbers and strings sort by Python's normal comparison rules.
def selection_sort(items):
items = items[:]
for start in range(len(items) - 1):
smallest = start
for i in range(start + 1, len(items)):
if items[i] < items[smallest]:
smallest = i
items[start], items[smallest] = items[smallest], items[start]
return items
print(selection_sort([5, 2, 5, 1, 2]))
print(selection_sort([3, -1, 0, -7]))
print(selection_sort(["pear", "apple", "fig"]))
print(selection_sort([]))Expected output[1, 2, 2, 5, 5]
[-7, -1, 0, 3]
['apple', 'fig', 'pear']
[]
Sort names typed by the user
The program reads comma-separated names, cleans them with strip() and sorts them alphabetically.
def selection_sort(items):
items = items[:]
for start in range(len(items) - 1):
smallest = start
for i in range(start + 1, len(items)):
if items[i] < items[smallest]:
smallest = i
items[start], items[smallest] = items[smallest], items[start]
return items
line = input("Names: ")
names = [name.strip() for name in line.split(",")]
print(selection_sort(names))Expected outputNames: Ravi, Asha, Meena, John
['Asha', 'John', 'Meena', 'Ravi']
Common mistakes
Swapping inside the inner loop
✗ Wrong
items = [3, 1, 2]
for start in range(len(items) - 1):
for i in range(start + 1, len(items)):
if items[i] < items[start]:
items[i], items[start] = items[start], items[i]
print(items)✓ Right
items = [3, 1, 2]
for start in range(len(items) - 1):
smallest = start
for i in range(start + 1, len(items)):
if items[i] < items[smallest]:
smallest = i
items[start], items[smallest] = items[smallest], items[start]
print(items)Find the index of the minimum first, then perform a single swap after the inner loop.
Sorting the caller's list by accident
✗ Wrong
def selection_sort(items):
for start in range(len(items) - 1):
smallest = start
for i in range(start + 1, len(items)):
if items[i] < items[smallest]:
smallest = i
items[start], items[smallest] = items[smallest], items[start]
return items
original = [3, 1, 2]
result = selection_sort(original)
print(original)✓ Right
def selection_sort(items):
items = items[:]
for start in range(len(items) - 1):
smallest = start
for i in range(start + 1, len(items)):
if items[i] < items[smallest]:
smallest = i
items[start], items[smallest] = items[smallest], items[start]
return items
original = [3, 1, 2]
result = selection_sort(original)
print(original)Copy first with items = items[:] or items.copy(), or document that the function sorts in place.
Python Selection Sort Program (with Explanation): questions people ask
What is the time complexity of selection sort?
Selection sort is O(n²) in the best, average and worst cases, because it always scans the whole unsorted part to find the minimum. It uses O(1) extra space.
What is the difference between selection sort and bubble sort?
Selection sort finds the minimum and makes one swap per round, while bubble sort swaps neighbouring pairs many times per pass. Bubble sort can stop early on sorted input; selection sort cannot.
Is selection sort stable?
The usual swap-based implementation is not stable: swapping the minimum to the front can change the relative order of equal items.
Keep learning
Step-by-step lessons:
Python Nested LoopsPython ListsPython Sorting
Related:
Python Bubble Sort Program (with Explanation)Python sorted() FunctionPython List sort() MethodPython min() Function
More in algorithms:
Python Program for Linear Search (with Examples)Python Binary Search Program (Iterative and Recursive)Python Bubble Sort Program (with Explanation)Python Tower of Hanoi Program (Recursion Explained) See all →