mirror of
https://github.com/TheAlgorithms/Python.git
synced 2024-11-23 21:11:08 +00:00
Updated Selection Sort (#10855)
* Update selection_sort.py * Update selection_sort.py
This commit is contained in:
parent
30122062b9
commit
ffd3a56c35
|
@ -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)
|
||||
|
|
Loading…
Reference in New Issue
Block a user