From c227ff95f540a939c0a6599b9887c69299054c8d Mon Sep 17 00:00:00 2001 From: Amirsoroush Date: Mon, 21 Aug 2023 19:09:18 +0300 Subject: [PATCH 1/2] fixes #9002; improve insertion_sort algorithm --- sorts/insertion_sort.py | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/sorts/insertion_sort.py b/sorts/insertion_sort.py index 6d5bb2b46013..ae17024d3dea 100644 --- a/sorts/insertion_sort.py +++ b/sorts/insertion_sort.py @@ -40,13 +40,12 @@ def insertion_sort(collection: list) -> list: True """ - for insert_index, insert_value in enumerate(collection[1:]): - temp_index = insert_index - while insert_index >= 0 and insert_value < collection[insert_index]: - collection[insert_index + 1] = collection[insert_index] + for insert_index in range(1, len(collection)): + insert_value = collection[insert_index] + while insert_index > 0 and insert_value < collection[insert_index - 1]: + collection[insert_index] = collection[insert_index - 1] insert_index -= 1 - if insert_index != temp_index: - collection[insert_index + 1] = insert_value + collection[insert_index] = insert_value return collection From 48af2473b31c6e1e8a04610d9e72abb70fa8e80c Mon Sep 17 00:00:00 2001 From: Amirsoroush Date: Mon, 21 Aug 2023 19:12:32 +0300 Subject: [PATCH 2/2] add type hints to sorts/insertion_sort.py --- sorts/insertion_sort.py | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/sorts/insertion_sort.py b/sorts/insertion_sort.py index ae17024d3dea..f11ddac349a0 100644 --- a/sorts/insertion_sort.py +++ b/sorts/insertion_sort.py @@ -13,8 +13,19 @@ 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 :param collection: some mutable ordered collection with heterogeneous