fixes #9002; improve insertion_sort algorithm (#9005)

* fixes #9002; improve insertion_sort algorithm

* add type hints to sorts/insertion_sort.py
This commit is contained in:
AmirSoroush 2023-08-22 02:17:02 +03:00 committed by GitHub
parent 1210559deb
commit b3dc6ef035
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -13,8 +13,19 @@ For manual testing run:
python3 insertion_sort.py python3 insertion_sort.py
""" """
from collections.abc import MutableSequence
from typing import Any, Protocol, TypeVar
def insertion_sort(collection: list) -> list:
class Comparable(Protocol):
def __lt__(self, other: Any, /) -> bool:
...
T = TypeVar("T", bound=Comparable)
def insertion_sort(collection: MutableSequence[T]) -> MutableSequence[T]:
"""A pure Python implementation of the insertion sort algorithm """A pure Python implementation of the insertion sort algorithm
:param collection: some mutable ordered collection with heterogeneous :param collection: some mutable ordered collection with heterogeneous
@ -40,13 +51,12 @@ def insertion_sort(collection: list) -> list:
True True
""" """
for insert_index, insert_value in enumerate(collection[1:]): for insert_index in range(1, len(collection)):
temp_index = insert_index insert_value = collection[insert_index]
while insert_index >= 0 and insert_value < collection[insert_index]: while insert_index > 0 and insert_value < collection[insert_index - 1]:
collection[insert_index + 1] = collection[insert_index] collection[insert_index] = collection[insert_index - 1]
insert_index -= 1 insert_index -= 1
if insert_index != temp_index: collection[insert_index] = insert_value
collection[insert_index + 1] = insert_value
return collection return collection