2023-10-04 02:07:25 +00:00
|
|
|
def selection_sort(collection: list[int]) -> list[int]:
|
2023-10-23 18:12:28 +00:00
|
|
|
"""
|
|
|
|
Sorts a list in ascending order using the selection sort algorithm.
|
2016-09-25 21:15:14 +00:00
|
|
|
|
2023-10-23 18:12:28 +00:00
|
|
|
:param collection: A list of integers to be sorted.
|
|
|
|
:return: The sorted list.
|
2016-07-29 10:58:23 +00:00
|
|
|
|
|
|
|
Examples:
|
|
|
|
>>> selection_sort([0, 5, 3, 2, 2])
|
|
|
|
[0, 2, 2, 3, 5]
|
|
|
|
|
|
|
|
>>> selection_sort([])
|
|
|
|
[]
|
|
|
|
|
|
|
|
>>> selection_sort([-2, -5, -45])
|
|
|
|
[-45, -5, -2]
|
|
|
|
"""
|
2016-09-25 21:15:14 +00:00
|
|
|
|
2016-07-29 20:06:49 +00:00
|
|
|
length = len(collection)
|
2018-10-07 09:03:56 +00:00
|
|
|
for i in range(length - 1):
|
2023-10-23 18:12:28 +00:00
|
|
|
min_index = i
|
2016-07-29 10:58:23 +00:00
|
|
|
for k in range(i + 1, length):
|
2023-10-23 18:12:28 +00:00
|
|
|
if collection[k] < collection[min_index]:
|
|
|
|
min_index = k
|
|
|
|
if min_index != i:
|
|
|
|
collection[i], collection[min_index] = collection[min_index], collection[i]
|
2016-07-29 20:06:49 +00:00
|
|
|
return collection
|
2016-07-29 10:58:23 +00:00
|
|
|
|
|
|
|
|
2019-10-05 05:14:13 +00:00
|
|
|
if __name__ == "__main__":
|
|
|
|
user_input = input("Enter numbers separated by a comma:\n").strip()
|
|
|
|
unsorted = [int(item) for item in user_input.split(",")]
|
2023-10-23 18:12:28 +00:00
|
|
|
sorted_list = selection_sort(unsorted)
|
|
|
|
print("Sorted List:", sorted_list)
|