Skip to content

Commit ffd3a56

Browse files
authored
Updated Selection Sort (#10855)
* Update selection_sort.py * Update selection_sort.py
1 parent 3012206 commit ffd3a56

File tree

1 file changed

+11
-23
lines changed

1 file changed

+11
-23
lines changed

Diff for: sorts/selection_sort.py

+11-23
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,9 @@
1-
"""
2-
This is a pure Python implementation of the selection sort algorithm
3-
4-
For doctests run following command:
5-
python -m doctest -v selection_sort.py
6-
or
7-
python3 -m doctest -v selection_sort.py
8-
9-
For manual testing run:
10-
python selection_sort.py
11-
"""
12-
13-
141
def selection_sort(collection: list[int]) -> list[int]:
15-
"""Pure implementation of the selection sort algorithm in Python
16-
:param collection: some mutable ordered collection with heterogeneous
17-
comparable items inside
18-
:return: the same collection ordered by ascending
2+
"""
3+
Sorts a list in ascending order using the selection sort algorithm.
194
5+
:param collection: A list of integers to be sorted.
6+
:return: The sorted list.
207
218
Examples:
229
>>> selection_sort([0, 5, 3, 2, 2])
@@ -31,16 +18,17 @@ def selection_sort(collection: list[int]) -> list[int]:
3118

3219
length = len(collection)
3320
for i in range(length - 1):
34-
least = i
21+
min_index = i
3522
for k in range(i + 1, length):
36-
if collection[k] < collection[least]:
37-
least = k
38-
if least != i:
39-
collection[least], collection[i] = (collection[i], collection[least])
23+
if collection[k] < collection[min_index]:
24+
min_index = k
25+
if min_index != i:
26+
collection[i], collection[min_index] = collection[min_index], collection[i]
4027
return collection
4128

4229

4330
if __name__ == "__main__":
4431
user_input = input("Enter numbers separated by a comma:\n").strip()
4532
unsorted = [int(item) for item in user_input.split(",")]
46-
print(selection_sort(unsorted))
33+
sorted_list = selection_sort(unsorted)
34+
print("Sorted List:", sorted_list)

0 commit comments

Comments
 (0)