ProgramAlgorithms

Python Selection Sort Program (with Explanation)

Short answer
Selection sort sorts a list by repeatedly finding the smallest remaining item and swapping it into the next position at the front. It always takes O(n²) comparisons but makes at most n − 1 swaps.

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.

Quick facts
InputA list of comparable items
OutputA new list sorted in ascending order
ApproachFind the minimum of the unsorted part, swap it to the front, shrink the unsorted part
Time complexityO(n²) in every case; O(1) extra space; at most n − 1 swaps

Approach: how selection sort works step by step

  1. Assume position 0 holds the smallest value.
  2. Scan the rest of the list; whenever you see something smaller, remember its index.
  3. Swap the smallest value found into position 0.
  4. Repeat from position 1, then 2, and so on.
  5. 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.

Python
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()

AspectSelection sortBubble sort`sorted()`
Best-case timeO(n²)O(n) with early exitO(n)
Worst-case timeO(n²)O(n²)O(n log n)
SwapsAt most n − 1Up to about n²/2Not applicable
Stable (keeps equal items in order)?No (in the usual form)YesYes

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.

Sort a list of marks
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.

Descending order by selecting the largest item
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.

Edge cases: duplicates, negatives and strings
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.

Sort names typed by the user
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)
No error, and the list does end up sorted, but this is not selection sort: it swaps many times per round (it behaves like a different, less efficient algorithm).

✓ 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)
[1, 2, 3] (the original list was changed as a side effect, which may surprise the caller)

✓ 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 →