Skip to content

Commit 0372abc

Browse files
sorts: type selection sort for comparable items (#15245)
* sorts: type selection sort for comparable items * style: remove unused TypeVar import * test: restore selection sort doctests
1 parent 927c7d3 commit 0372abc

1 file changed

Lines changed: 17 additions & 4 deletions

File tree

sorts/selection_sort.py

Lines changed: 17 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,12 @@
1-
def selection_sort(collection: list[int]) -> list[int]:
1+
from collections.abc import MutableSequence
2+
from typing import Any, Protocol
3+
4+
5+
class Comparable(Protocol):
6+
def __lt__(self, other: Any, /) -> bool: ...
7+
8+
9+
def selection_sort[T: Comparable](collection: MutableSequence[T]) -> MutableSequence[T]:
210
"""
311
Sorts a list in ascending order using the selection sort algorithm.
412
@@ -9,8 +17,8 @@ def selection_sort(collection: list[int]) -> list[int]:
917
Time Complexity: O(n²) in all cases
1018
Space Complexity: O(1)
1119
12-
:param collection: A list of comparable items to be sorted.
13-
:return: The same list sorted in ascending order.
20+
:param collection: A mutable sequence of comparable items to be sorted.
21+
:return: The same sequence sorted in ascending order.
1422
1523
Examples:
1624
>>> selection_sort([0, 5, 3, 2, 2])
@@ -45,8 +53,13 @@ def selection_sort(collection: list[int]) -> list[int]:
4553
4654
>>> selection_sort([-2, -5, -45]) == sorted([-2, -5, -45])
4755
True
48-
"""
4956
57+
>>> selection_sort(["d", "a", "c", "b"])
58+
['a', 'b', 'c', 'd']
59+
60+
>>> selection_sort([3.2, 1.1, 2.4, 0.5])
61+
[0.5, 1.1, 2.4, 3.2]
62+
"""
5063
length = len(collection)
5164
for i in range(length - 1):
5265
min_index = i

0 commit comments

Comments
 (0)