Loading...

Python Program to Implement Selection Sort

By Coder Scratchpad on in Python

Python Program to Implement Selection Sort

When you start learning Python programming, understanding sorting algorithms is one of the first steps to mastering data manipulation. Sorting helps organize data in a specific order, such as ascending or descending, which is essential in almost every software application. Selection Sort is a classic sorting algorithm that is simple to understand and perfect for beginners who want to see the logic behind arranging data step by step.

Selection Sort works by repeatedly finding the smallest (or largest) element from the unsorted portion of the list and placing it in its correct position. It is often used in educational settings to teach the principles of sorting because its process is straightforward and easy to visualize. While not the fastest algorithm for large datasets, it is a great way to practice Python loops, conditionals, and swapping elements.

Table of Contents

Toggle
  • Program 1: Selection Sort Using Loops
  • Program 2: Selection Sort in Descending Order
  • Program 3: Selection Sort Using Recursion
  • Program 4: Selection Sort Using a Key Function
  • Program 5: Selection Sort for Custom Objects
  • Frequently Asked Questions (FAQ)
  • Conclusion

Program 1: Selection Sort Using Loops

This program demonstrates the basic loop-based approach to Selection Sort. It scans the list repeatedly to find the minimum element and swaps it into its correct position with each pass.

def selection_sort(arr):

    n = len(arr)

    for i in range(n):

        min_idx = i

        for j in range(i+1, n):

            if arr[j] < arr[min_idx]:
                min_idx = j

        arr[i], arr[min_idx] = arr[min_idx], arr[i]

    return arr


numbers = [64, 25, 12, 22, 11]

sorted_numbers = selection_sort(numbers)

print("Sorted list:", sorted_numbers)
def selection_sort(arr):

    n = len(arr)

    for i in range(n):

        min_idx = i

        for j in range(i+1, n):

            if arr[j] < arr[min_idx]:
                min_idx = j

        arr[i], arr[min_idx] = arr[min_idx], arr[i]

    return arr


numbers = [64, 25, 12, 22, 11]

sorted_numbers = selection_sort(numbers)

print("Sorted list:", sorted_numbers)

 

In this program, the outer loop marks the position where the next smallest element should go, while the inner loop searches for the minimum element in the unsorted part of the list. Once found, a simple swap places it in the correct position. Beginners will find this approach useful because it clearly separates the process of finding the minimum element and arranging it step by step.

Program 2: Selection Sort in Descending Order

Sometimes, we need to sort a list from largest to smallest. This version of Selection Sort finds the maximum element in each pass and moves it to its correct position at the start of the list.

def selection_sort_desc(arr):

    n = len(arr)

    for i in range(n):

        max_idx = i

        for j in range(i+1, n):

            if arr[j] > arr[max_idx]:
                max_idx = j

        arr[i], arr[max_idx] = arr[max_idx], arr[i]

    return arr


numbers = [10, 50, 30, 20, 40]

sorted_numbers = selection_sort_desc(numbers)

print("Sorted list in descending order:", sorted_numbers)
def selection_sort_desc(arr):

    n = len(arr)

    for i in range(n):

        max_idx = i

        for j in range(i+1, n):

            if arr[j] > arr[max_idx]:
                max_idx = j

        arr[i], arr[max_idx] = arr[max_idx], arr[i]

    return arr


numbers = [10, 50, 30, 20, 40]

sorted_numbers = selection_sort_desc(numbers)

print("Sorted list in descending order:", sorted_numbers)

 

This variant teaches beginners how a small change in logic can completely change the outcome of an algorithm. Sorting in descending order is often a requirement in real-world applications, such as ranking scores or prices.

Program 3: Selection Sort Using Recursion

Selection Sort can also be implemented recursively. The recursive approach simplifies the concept into smaller problems, sorting one element at a time and then calling itself for the remaining list.

def recursive_selection_sort(arr, start=0):

    n = len(arr)

    if start >= n - 1:
        return arr

    min_idx = start

    for i in range(start+1, n):

        if arr[i] < arr[min_idx]:
            min_idx = i

    arr[start], arr[min_idx] = arr[min_idx], arr[start]

    return recursive_selection_sort(arr, start + 1)


numbers = [29, 10, 14, 37, 13]

sorted_numbers = recursive_selection_sort(numbers)

print("Sorted list using recursion:", sorted_numbers)
def recursive_selection_sort(arr, start=0):

    n = len(arr)

    if start >= n - 1:
        return arr

    min_idx = start

    for i in range(start+1, n):

        if arr[i] < arr[min_idx]:
            min_idx = i

    arr[start], arr[min_idx] = arr[min_idx], arr[start]

    return recursive_selection_sort(arr, start + 1)


numbers = [29, 10, 14, 37, 13]

sorted_numbers = recursive_selection_sort(numbers)

print("Sorted list using recursion:", sorted_numbers)

 

In this recursive version, the function finds the minimum element for the current starting index and swaps it with the first unsorted element. Then, it calls itself to sort the rest of the list. This method is useful for beginners to practice recursion and see how iterative processes can be converted into recursive logic.

Program 4: Selection Sort Using a Key Function

Python allows flexible sorting by customizing a “key” function. This example sorts a list of numbers based on their absolute values.

def selection_sort_by_key(arr, key_func):

    n = len(arr)

    for i in range(n - 1):

        min_index = i

        for j in range(i + 1, n):

            if key_func(arr[j]) < key_func(arr[min_index]):
                min_index = j

        arr[i], arr[min_index] = arr[min_index], arr[i]


numbers = [-10, 2, -30, 4, 5]

selection_sort_by_key(numbers, key_func=abs)

print("Sorted by absolute value:", numbers)
def selection_sort_by_key(arr, key_func):

    n = len(arr)

    for i in range(n - 1):

        min_index = i

        for j in range(i + 1, n):

            if key_func(arr[j]) < key_func(arr[min_index]):
                min_index = j

        arr[i], arr[min_index] = arr[min_index], arr[i]


numbers = [-10, 2, -30, 4, 5]

selection_sort_by_key(numbers, key_func=abs)

print("Sorted by absolute value:", numbers)

 

Using a key function shows beginners how to adapt Selection Sort to different sorting criteria, making the algorithm versatile for various real-world scenarios.

Program 5: Selection Sort for Custom Objects

Selection Sort can also sort objects based on an attribute. This example sorts a list of Person objects by their age.

class Person:

    def __init__(self, name, age):
        self.name = name
        self.age = age

    def __repr__(self):
        return f"{self.name} ({self.age})"


def selection_sort_objects(arr, key_func):

    n = len(arr)

    for i in range(n - 1):

        min_index = i

        for j in range(i + 1, n):

            if key_func(arr[j]) < key_func(arr[min_index]):
                min_index = j

        arr[i], arr[min_index] = arr[min_index], arr[i]


people = [Person("Mary", 25), Person("Samantha", 20), Person("Edward", 30)]

selection_sort_objects(people, key_func=lambda p: p.age)

print("Sorted by age:", people)
class Person:

    def __init__(self, name, age):
        self.name = name
        self.age = age

    def __repr__(self):
        return f"{self.name} ({self.age})"


def selection_sort_objects(arr, key_func):

    n = len(arr)

    for i in range(n - 1):

        min_index = i

        for j in range(i + 1, n):

            if key_func(arr[j]) < key_func(arr[min_index]):
                min_index = j

        arr[i], arr[min_index] = arr[min_index], arr[i]


people = [Person("Mary", 25), Person("Samantha", 20), Person("Edward", 30)]

selection_sort_objects(people, key_func=lambda p: p.age)

print("Sorted by age:", people)

 

This demonstrates how Selection Sort can handle complex data, teaching beginners how to combine algorithmic logic with object-oriented programming.

Frequently Asked Questions (FAQ)

Understanding Selection Sort often raises a few questions for beginners. Here are some answers to help you grasp it better.

Q1: Is Selection Sort efficient for large lists?
Selection Sort has a time complexity of O(n²), so it is best suited for small arrays or learning purposes. For larger datasets, algorithms like Quick Sort or Merge Sort are recommended.

Q2: Can Selection Sort handle objects?
Yes. Using a key function or attribute-based comparison, Selection Sort can sort objects like dictionaries, classes, or custom data structures.

Q3: Why use recursion for Selection Sort?
Recursive implementations help learners understand recursion and problem decomposition, even though iterative versions are usually more practical.

Q4: Can I sort in descending order?
Absolutely. Adjusting the comparison logic allows you to sort in ascending or descending order.

Q5: What is the benefit of using a key function?
Key functions make the algorithm flexible, enabling sorting based on different attributes or criteria without rewriting the core logic.

Conclusion

Selection Sort is an excellent algorithm for beginners learning sorting in Python. By exploring variations like ascending, descending, recursive, key-based, and object-based implementations, learners gain a deeper understanding of algorithm design and Python programming concepts. Practicing these programs builds confidence and prepares you to tackle more advanced sorting algorithms like Quick Sort, Merge Sort, and Heap Sort. The key is to experiment and watch how data becomes organized step by step—it’s a rewarding way to learn programming fundamentals.

Share this article