Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 11 additions & 23 deletions sorts/selection_sort.py
Original file line number Diff line number Diff line change
@@ -1,22 +1,9 @@
"""
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: list[int]) -> list[int]:
"""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
"""
Sorts a list in ascending order using the selection sort algorithm.

:param collection: A list of integers to be sorted.
:return: The sorted list.

Examples:
>>> selection_sort([0, 5, 3, 2, 2])
Expand All @@ -31,16 +18,17 @@ def selection_sort(collection: list[int]) -> list[int]:

length = len(collection)
for i in range(length - 1):
least = i
min_index = 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])
if collection[k] < collection[min_index]:
min_index = k
if min_index != i:
collection[i], collection[min_index] = collection[min_index], collection[i]
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))
sorted_list = selection_sort(unsorted)
print("Sorted List:", sorted_list)