selection sort Algorithm

Selection sort is a simple comparison-based sorting algorithm that is easy to understand and implement. The key idea behind the algorithm is to divide the input list into two parts – a sorted part and an unsorted part. Initially, the sorted part is empty, and the unsorted part contains all the elements. The algorithm repeatedly selects the smallest or largest (depending on the desired order) element from the unsorted part and moves it to the end of the sorted part. This process continues until the unsorted part becomes empty, and the sorted part contains all the elements in the desired order. In each iteration of the selection sort algorithm, it searches for the minimum or maximum element in the unsorted part of the list and swaps it with the first unsorted element. The time complexity of the selection sort algorithm is O(n^2) for the best, worst, and average cases, making it inefficient for large datasets. However, it performs well for small datasets or lists that are already partially sorted. One of the advantages of the selection sort algorithm is that it performs the minimum number of swaps, making it useful in situations where the cost of swapping elements is high. Despite its simplicity, selection sort is generally not used in practice because other sorting algorithms, such as quicksort and merge sort, have better overall performance.
"""
This is a pure Python implementation of the selection sort algorithm

For doctests run following command:
python -m doctest -v selection_sort.py
or
python3 -m doctest -v selection_sort.py

For manual testing run:
python selection_sort.py
"""


def selection_sort(collection):
    """Pure implementation of the selection sort algorithm in Python
    :param collection: some mutable ordered collection with heterogeneous
    comparable items inside
    :return: the same collection ordered by ascending


    Examples:
    >>> selection_sort([0, 5, 3, 2, 2])
    [0, 2, 2, 3, 5]

    >>> selection_sort([])
    []

    >>> selection_sort([-2, -5, -45])
    [-45, -5, -2]
    """

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

LANGUAGE:

DARK MODE: