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]:
|
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
|
Sorts a list in ascending order using the selection sort algorithm.
|
||||||
comparable items inside
|
|
||||||
:return: the same collection ordered by ascending
|
|
||||||
|
|
||||||
|
:param collection: A list of integers to be sorted.
|
||||||
|
:return: The sorted list.
|
||||||
|
|
||||||
Examples:
|
Examples:
|
||||||
>>> selection_sort([0, 5, 3, 2, 2])
|
>>> selection_sort([0, 5, 3, 2, 2])
|
||||||
|
@ -31,16 +18,17 @@ def selection_sort(collection: list[int]) -> list[int]:
|
||||||
|
|
||||||
length = len(collection)
|
length = len(collection)
|
||||||
for i in range(length - 1):
|
for i in range(length - 1):
|
||||||
least = i
|
min_index = i
|
||||||
for k in range(i + 1, length):
|
for k in range(i + 1, length):
|
||||||
if collection[k] < collection[least]:
|
if collection[k] < collection[min_index]:
|
||||||
least = k
|
min_index = k
|
||||||
if least != i:
|
if min_index != i:
|
||||||
collection[least], collection[i] = (collection[i], collection[least])
|
collection[i], collection[min_index] = collection[min_index], collection[i]
|
||||||
return collection
|
return collection
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
user_input = input("Enter numbers separated by a comma:\n").strip()
|
user_input = input("Enter numbers separated by a comma:\n").strip()
|
||||||
unsorted = [int(item) for item in user_input.split(",")]
|
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