Skip to content

Commit db52ade

Browse files
committed
Make gnome sort generic over comparable items
1 parent 9e1cf59 commit db52ade

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
@@ -96,6 +96,7 @@ def test_sort_matches_builtin(sort, case):
9696
bubble_sort_iterative,
9797
bubble_sort_recursive,
9898
circle_sort,
99+
gnome_sort,
99100
insertion_sort,
100101
merge_sort,
101102
selection_sort,

0 commit comments

Comments
 (0)