Skip to content

Commit 3790faa

Browse files
committed
Make gnome sort generic over comparable items
1 parent 9e84598 commit 3790faa

2 files changed

Lines changed: 9 additions & 2 deletions

File tree

sorts/gnome_sort.py

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,8 +12,14 @@
1212
python3 gnome_sort.py
1313
"""
1414

15+
from typing import Protocol
1516

16-
def gnome_sort(lst: list) -> list:
17+
18+
class Comparable(Protocol):
19+
def __lt__(self, other: object, /) -> bool: ...
20+
21+
22+
def gnome_sort[T: Comparable](lst: list[T]) -> list[T]:
1723
"""
1824
Pure implementation of the gnome sort algorithm in Python
1925
@@ -39,7 +45,7 @@ def gnome_sort(lst: list) -> list:
3945
i = 1
4046

4147
while i < len(lst):
42-
if lst[i - 1] <= lst[i]:
48+
if not lst[i] < lst[i - 1]:
4349
i += 1
4450
else:
4551
lst[i - 1], lst[i] = lst[i], lst[i - 1]

tests/test_sorts.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -95,6 +95,7 @@ def test_sort_matches_builtin(sort, case):
9595
binary_insertion_sort,
9696
bubble_sort_iterative,
9797
bubble_sort_recursive,
98+
gnome_sort,
9899
insertion_sort,
99100
],
100101
ids=lambda f: f.__name__,

0 commit comments

Comments
 (0)