Skip to content

Commit 6a8f4ed

Browse files
authored
Make gnome sort generic over comparable items (#15261)
1 parent 43cb26c commit 6a8f4ed

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
@@ -115,6 +115,7 @@ def test_sort_matches_builtin(sort, case):
115115
bubble_sort_iterative,
116116
bubble_sort_recursive,
117117
circle_sort,
118+
gnome_sort,
118119
insertion_sort,
119120
merge_sort,
120121
selection_sort,

0 commit comments

Comments
 (0)