2023-10-04 11:07:25 +09:00
|
|
|
def selection_sort(collection: list[int]) -> list[int]:
|
2023-10-23 23:42:28 +05:30
|
|
|
"""
|
|
|
|
Sorts a list in ascending order using the selection sort algorithm.
|
2016-09-26 02:45:14 +05:30
|
|
|
|
2023-10-23 23:42:28 +05:30
|
|
|
:param collection: A list of integers to be sorted.
|
|
|
|
:return: The sorted list.
|
2016-07-29 15:58:23 +05: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-26 02:45:14 +05:30
|
|
|
|
2016-07-30 01:06:49 +05:00
|
|
|
length = len(collection)
|
2018-10-07 14:33:56 +05:30
|
|
|
for i in range(length - 1):
|
2023-10-23 23:42:28 +05:30
|
|
|
min_index = i
|
2016-07-29 15:58:23 +05:00
|
|
|
for k in range(i + 1, length):
|
2023-10-23 23:42:28 +05:30
|
|
|
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-30 01:06:49 +05:00
|
|
|
return collection
|
2016-07-29 15:58:23 +05:00
|
|
|
|
|
|
|
|
2019-10-05 01:14:13 -04: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 23:42:28 +05:30
|
|
|
sorted_list = selection_sort(unsorted)
|
|
|
|
print("Sorted List:", sorted_list)
|