From 3c89b8a3c21da47dcb28988b2dff9c58e9b53e23 Mon Sep 17 00:00:00 2001 From: Harsh Raj Singhania Date: Sat, 12 Sep 2026 21:04:45 +0530 Subject: [PATCH] sorts: type shell_sort for comparable items and add tests --- sorts/shell_sort.py | 18 +++++++++++++++++- tests/test_sorts.py | 1 + 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/sorts/shell_sort.py b/sorts/shell_sort.py index b65609c974b7..c6574f62b1c7 100644 --- a/sorts/shell_sort.py +++ b/sorts/shell_sort.py @@ -2,8 +2,15 @@ https://en.wikipedia.org/wiki/Shellsort#Pseudocode """ +from collections.abc import MutableSequence +from typing import Any, Protocol -def shell_sort(collection: list[int]) -> list[int]: + +class Comparable(Protocol): + def __lt__(self, other: Any, /) -> bool: ... + + +def shell_sort[T: Comparable](collection: MutableSequence[T]) -> MutableSequence[T]: """Pure implementation of shell sort algorithm in Python :param collection: Some mutable ordered collection with heterogeneous comparable items inside @@ -15,6 +22,15 @@ def shell_sort(collection: list[int]) -> list[int]: [] >>> shell_sort([-2, -5, -45]) [-45, -5, -2] + >>> shell_sort(["c", "a", "b"]) + ['a', 'b', 'c'] + >>> shell_sort([2.5, -1, 0.0]) + [-1, 0.0, 2.5] + >>> shell_sort(["c", "a", "b"]) == sorted(["c", "a", "b"]) + True + >>> import pytest + >>> with pytest.raises(TypeError): + ... shell_sort([1, "a"]) """ # Marcin Ciura's gap sequence diff --git a/tests/test_sorts.py b/tests/test_sorts.py index adabc2c7d43a..2e5921aab8ea 100644 --- a/tests/test_sorts.py +++ b/tests/test_sorts.py @@ -121,6 +121,7 @@ def test_sort_matches_builtin(sort, case): insertion_sort, merge_sort, selection_sort, + shell_sort, ], ids=lambda f: f.__name__, )