Python Selection Sort


Selection sort is another simple and beginner-friendly sorting algorithm that helps you understand how sorting works behind the scenes. Instead of swapping elements repeatedly like bubble sort, this method searches for the smallest element in the list and places it at the correct position. It builds the sorted list one element at a time.

In this tutorial, you’ll learn how selection sort works, how the smallest value is chosen in each pass, how to implement it in Python and where it is commonly used. This lesson continues your foundation for more advanced sorting techniques.

What Is Selection Sort?

Selection sort is a sorting algorithm that divides the list into two parts:

  • A sorted section (left side)

  • An unsorted section (right side)

During each step, the algorithm finds the smallest element from the unsorted part and moves it into the sorted part. This continues until all elements are arranged in order.

The process is simple and predictable, which makes selection sort great for learning and understanding the basics of sorting.

How Selection Sort Works Step by Step

Let’s take this list:

[7, 4, 9, 2]

The algorithm follows these steps:

Pass 1

  1. Look through all elements to find the smallest value → 2

  2. Swap 2 with the first element

  3. List becomes: [2, 4, 9, 7]

Pass 2

  1. Find the smallest in the remaining part [4, 9, 7] → 4

  2. Already in the correct position

  3. List stays the same

Pass 3

  1. Find the smallest in [9, 7] → 7

  2. Swap 7 with 9

  3. Final list: [2, 4, 7, 9]

Each pass selects one element and puts it where it belongs.

Why Use Selection Sort?

Even though selection sort isn’t the fastest algorithm, it has some nice advantages:

  • Easy to understand

  • Good for teaching algorithm logic

  • Makes a fixed number of comparisons

  • Works well for small datasets

  • Uses very little memory

Because it always scans the entire remaining list, it behaves predictably and is simple to analyze.

Selection Sort Using a Loop

Here’s the basic version:

def selection_sort(data):
    n = len(data)

    for i in range(n):
        min_index = i

        for j in range(i + 1, n):
            if data[j] < data[min_index]:
                min_index = j

        data[i], data[min_index] = data[min_index], data[i]

    return data

This approach finds the smallest value and swaps it into place.

Example Usage

numbers = [8, 3, 5, 1, 9]
sorted_list = selection_sort(numbers)
print(sorted_list)

Output:

[1, 3, 5, 8, 9]

This confirms that the algorithm places each element where it belongs.

Time Complexity of Selection Sort

Selection sort performs the same number of comparisons no matter how sorted the list is.

  • Best case: O(n²)

  • Worst case: O(n²)

  • Average case: O(n²)

Because of this, selection sort is not ideal for large lists, but it is great for understanding how sorting works.

When Selection Sort Works Best

Selection sort is useful when:

  • The dataset is small

  • Memory usage needs to stay low

  • Swapping cost is low

  • You’re teaching or learning sorting fundamentals

  • Predictable performance is needed

Because it always does the same number of passes, its behavior is easy to follow.

When Selection Sort Is Not Suitable

Avoid this algorithm when:

  • You’re dealing with large datasets

  • Performance is critical

  • You need fast sorting

  • Frequent updates occur

Algorithms like quick sort, merge sort or insertion sort perform better in these cases.

Real-Life Uses of Selection Sort

Although not common in high-performance systems, selection sort appears in several areas:

Teaching environments

It helps students understand index-based sorting.

Hardware-level operations

Some simple hardware systems use selection-like logic.

Sorting very small lists

Microcontrollers or basic embedded devices sometimes use it.

Demonstrations and animations

Selection sort often appears in visual algorithm demos.

Learning pass-by-pass improvements

It shows how to choose and place the correct item each time.

Step-by-Step Example

List:

[6, 1, 4, 3]

Pass 1:

  • Smallest in entire list → 1

  • Swap 1 with 6 → [1, 6, 4, 3]

Pass 2:

  • Smallest in [6, 4, 3] → 3

  • Swap 3 with 6 → [1, 3, 4, 6]

Pass 3:

  • Smallest in [4, 6] → 4

  • Already in place

Final list:

[1, 3, 4, 6]

This example shows how each element is placed where it belongs.

Practical Examples

Example 1: Sort integers

print(selection_sort([9, 2, 8, 1]))

Example 2: Sort strings alphabetically

texts = ["pear", "apple", "mango"]
print(selection_sort(texts))

Example 3: Sort floating values

values = [3.4, 1.2, 5.8, 2.9]
print(selection_sort(values))

Example 4: Sort names in a class list

names = ["Asha", "Diya", "Riya"]
print(selection_sort(names))

Example 5: Sort a list manually entered by a user

data = [int(x) for x in "7 3 1 9".split()]
print(selection_sort(data))

Example 6: Sort tuple pairs by number

pairs = [(3,"x"), (1,"y"), (2,"z")]
print(selection_sort(pairs))

Example 7: Sort scores ascending

scores = [55, 78, 32, 90]
print(selection_sort(scores))

Example 8: Sort letters

letters = ['d', 'b', 'c', 'a']
print(selection_sort(letters))

Example 9: Sort very small embedded dataset

tiny = [3, 1]
print(selection_sort(tiny))

Example 10: Sort product prices

prices = [120, 40, 75, 10]
print(selection_sort(prices))

Summary of the Tutorial

Selection sort works by repeatedly selecting the smallest element from the unsorted part of the list and placing it in the correct position. You learned how the algorithm moves step by step, how to write the Python implementation, when to use it, when to avoid it and how it behaves in real examples. Even though it’s not the fastest, it plays an important role in building a strong base in sorting algorithms.


Practice Questions

Q1. Write a Python program to sort the list [9, 5, 2, 6, 8] using selection sort.

Q2. Write a Python program to modify the selection sort function to sort a list in descending order.

Q3. Write a Python program to sort a list of names alphabetically using selection sort.

Q4. Write a Python program to print each step (pass) of the selection sort process.

Q5. Write a Python program to accept a list of numbers from the user and sort it using selection sort.

Q6. Write a Python program to track and print how many swaps occur during the selection sort.

Q7. Write a Python program to count and display the total number of comparisons made in selection sort.

Q8. Write a Python program to sort a list of dictionaries by a specific value (e.g., age) using selection sort logic.

Q9. Write a Python program to sort a list of strings in a case-insensitive manner using selection sort.

Q10. Write a Python program to measure and print the time taken to sort a list of 1,000 random numbers using selection sort.


Try a Short Quiz.

coding learning websites codepractice

No quizzes available.

Go Back Top