Skip to content

Commit d502013

Browse files
otrishacclauss
andauthored
sorts: make comb_sort generic for comparable items (#15288)
* sorts: make comb sort generic for comparable items * tests: cover comb sort incomparable inputs * Update sorts/comb_sort.py * Apply suggestion from @cclauss * Apply suggestion from @cclauss --------- Co-authored-by: Christian Clauss <cclauss@me.com>
1 parent 3e34e8e commit d502013

2 files changed

Lines changed: 17 additions & 2 deletions

File tree

sorts/comb_sort.py

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,8 +18,14 @@
1818
python comb_sort.py
1919
"""
2020

21+
from typing import Any, Protocol
2122

22-
def comb_sort(data: list) -> list:
23+
24+
class Comparable(Protocol):
25+
def __lt__(self, other: Any, /) -> bool: ...
26+
27+
28+
def comb_sort[T: Comparable](data: list[T]) -> list[T]:
2329
"""Pure implementation of comb sort algorithm in Python
2430
:param data: mutable collection with comparable items
2531
:return: the same collection in ascending order
@@ -32,6 +38,14 @@ def comb_sort(data: list) -> list:
3238
[-15, -7, 0, 2, 3, 8, 45, 99]
3339
>>> comb_sort([2, 0, 3, 4, 5, 6, 1])
3440
[0, 1, 2, 3, 4, 5, 6]
41+
>>> comb_sort(["c", "a", "b"])
42+
['a', 'b', 'c']
43+
>>> comb_sort([2.5, -1, 0.0])
44+
[-1, 0.0, 2.5]
45+
>>> comb_sort([1, "a"])
46+
Traceback (most recent call last):
47+
...
48+
TypeError: '<' not supported between instances of 'str' and 'int'
3549
"""
3650
shrink_factor = 1.3
3751
gap = len(data)
@@ -47,7 +61,7 @@ def comb_sort(data: list) -> list:
4761

4862
index = 0
4963
while index + gap < len(data):
50-
if data[index] > data[index + gap]:
64+
if data[index + gap] < data[index]:
5165
# Swap values
5266
data[index], data[index + gap] = data[index + gap], data[index]
5367
completed = False

tests/test_sorts.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -116,6 +116,7 @@ def test_sort_matches_builtin(sort, case):
116116
bubble_sort_recursive,
117117
circle_sort,
118118
cocktail_shaker_sort,
119+
comb_sort,
119120
gnome_sort,
120121
insertion_sort,
121122
merge_sort,

0 commit comments

Comments
 (0)