Updated Selection Sort (#10855)

* Update selection_sort.py

* Update selection_sort.py
This commit is contained in:
SEIKH NABAB UDDIN 2023-10-23 23:42:28 +05:30 committed by GitHub
parent 30122062b9
commit ffd3a56c35
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

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