Selection Sort Algorithm in Python

In this source code example, we will write a code in Python to implement the Selection Sort algorithm.

The selection sort algorithm sorts an array by repeatedly finding the minimum element (considering ascending order) from the unsorted part and putting it at the beginning.

Python implementation of the Selection Sort algorithm

In this Python program, we will take input from the User or console and print the result to the output:
def selection_sort(collection):

    length = len(collection)
    for i in range(length - 1):
        least = i
        for k in range(i + 1, length):
            if collection[k] < collection[least]:
                least = k
        if least != i:
            collection[least], collection[i] = (collection[i], collection[least])
    return collection


if __name__ == "__main__":
    user_input = input("Enter numbers separated by a comma:\n").strip()
    unsorted = [int(item) for item in user_input.split(",")]
    print(selection_sort(unsorted))

Output:

Enter numbers separated by a comma:
10, 5, 9, 4, 5 2
[2, 4, 5, 9, 10]

Related Algorithms in Python