Skip to content

fixes #9002; improve insertion_sort algorithm #9005

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Aug 21, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 17 additions & 7 deletions sorts/insertion_sort.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -40,13 +51,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


Expand Down