Skip to content

Commit b3dc6ef

Browse files
authored
fixes #9002; improve insertion_sort algorithm (#9005)
* fixes #9002; improve insertion_sort algorithm * add type hints to sorts/insertion_sort.py
1 parent 1210559 commit b3dc6ef

File tree

1 file changed

+17
-7
lines changed

1 file changed

+17
-7
lines changed

Diff for: sorts/insertion_sort.py

+17-7
Original file line numberDiff line numberDiff line change
@@ -13,8 +13,19 @@
1313
python3 insertion_sort.py
1414
"""
1515

16+
from collections.abc import MutableSequence
17+
from typing import Any, Protocol, TypeVar
1618

17-
def insertion_sort(collection: list) -> list:
19+
20+
class Comparable(Protocol):
21+
def __lt__(self, other: Any, /) -> bool:
22+
...
23+
24+
25+
T = TypeVar("T", bound=Comparable)
26+
27+
28+
def insertion_sort(collection: MutableSequence[T]) -> MutableSequence[T]:
1829
"""A pure Python implementation of the insertion sort algorithm
1930
2031
:param collection: some mutable ordered collection with heterogeneous
@@ -40,13 +51,12 @@ def insertion_sort(collection: list) -> list:
4051
True
4152
"""
4253

43-
for insert_index, insert_value in enumerate(collection[1:]):
44-
temp_index = insert_index
45-
while insert_index >= 0 and insert_value < collection[insert_index]:
46-
collection[insert_index + 1] = collection[insert_index]
54+
for insert_index in range(1, len(collection)):
55+
insert_value = collection[insert_index]
56+
while insert_index > 0 and insert_value < collection[insert_index - 1]:
57+
collection[insert_index] = collection[insert_index - 1]
4758
insert_index -= 1
48-
if insert_index != temp_index:
49-
collection[insert_index + 1] = insert_value
59+
collection[insert_index] = insert_value
5060
return collection
5161

5262

0 commit comments

Comments
 (0)