sorts.selection_sort

Attributes

user_input

Classes

Comparable

Base class for protocol classes.

Functions

selection_sort(→ collections.abc.MutableSequence[T])

Sorts a list in ascending order using the selection sort algorithm.

Module Contents

class sorts.selection_sort.Comparable

Bases: Protocol

Base class for protocol classes.

Protocol classes are defined as:

class Proto(Protocol):
    def meth(self) -> int:
        ...

Such classes are primarily used with static type checkers that recognize structural subtyping (static duck-typing).

For example:

class C:
    def meth(self) -> int:
        return 0

def func(x: Proto) -> int:
    return x.meth()

func(C())  # Passes static type check

See PEP 544 for details. Protocol classes decorated with @typing.runtime_checkable act as simple-minded runtime protocols that check only the presence of given attributes, ignoring their type signatures. Protocol classes can be generic, they are defined as:

class GenProto[T](Protocol):
    def meth(self) -> T:
        ...
__lt__(other: Any, /) bool
sorts.selection_sort.selection_sort[T: Comparable](collection: collections.abc.MutableSequence[T]) collections.abc.MutableSequence[T]

Sorts a list in ascending order using the selection sort algorithm.

Selection sort divides the input list into a sorted and unsorted region. It repeatedly finds the minimum element from the unsorted region and places it at the end of the sorted region.

Time Complexity: O(n²) in all cases Space Complexity: O(1)

Parameters:

collection – A mutable sequence of comparable items to be sorted.

Returns:

The same sequence sorted in ascending order.

Time Complexity: O(n^2) - Due to the nested loops, where n is the length

of the collection. The outer loop runs n-1 times, and the inner loop runs n-i-1 times for each iteration.

Space Complexity: O(1) - Only a constant amount of extra space is used

for variables (length, i, min_index, k).

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

>>> selection_sort([])
[]
>>> selection_sort([-2, -5, -45])
[-45, -5, -2]
>>> selection_sort([1])
[1]
>>> selection_sort([5, 4, 3, 2, 1])
[1, 2, 3, 4, 5]
>>> selection_sort([1, 2, 3, 4, 5])
[1, 2, 3, 4, 5]
>>> selection_sort([3, 3, 3, 3])
[3, 3, 3, 3]
>>> selection_sort([0])
[0]
>>> selection_sort([2, -3, 0, 5, -1])
[-3, -1, 0, 2, 5]
>>> selection_sort([0, 5, 3, 2, 2]) == sorted([0, 5, 3, 2, 2])
True
>>> selection_sort([-2, -5, -45]) == sorted([-2, -5, -45])
True
>>> selection_sort(["d", "a", "c", "b"])
['a', 'b', 'c', 'd']
>>> selection_sort([3.2, 1.1, 2.4, 0.5])
[0.5, 1.1, 2.4, 3.2]
sorts.selection_sort.user_input