Skip to content
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 16 additions & 2 deletions sorts/comb_sort.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,14 @@
python comb_sort.py
"""

from typing import Any, Protocol

def comb_sort(data: list) -> list:

class Comparable(Protocol):
def __lt__(self, other: Any, /) -> bool: ...


def comb_sort[T: Comparable](data: list[T]) -> list[T]:
"""Pure implementation of comb sort algorithm in Python
:param data: mutable collection with comparable items
:return: the same collection in ascending order
Expand All @@ -32,6 +38,14 @@ def comb_sort(data: list) -> list:
[-15, -7, 0, 2, 3, 8, 45, 99]
>>> comb_sort([2, 0, 3, 4, 5, 6, 1])
[0, 1, 2, 3, 4, 5, 6]
>>> comb_sort(["c", "a", "b"])
['a', 'b', 'c']
>>> comb_sort([2.5, -1, 0.0])
[-1.0, 0.0, 2.5]
Comment thread
cclauss marked this conversation as resolved.
Outdated
>>> comb_sort([1, "a"])
Traceback (most recent call last):
...
TypeError: '<' not supported between instances of 'str' and 'int'
"""
shrink_factor = 1.3
gap = len(data)
Expand All @@ -47,7 +61,7 @@ def comb_sort(data: list) -> list:

index = 0
while index + gap < len(data):
if data[index] > data[index + gap]:
if data[index + gap] < data[index]:
# Swap values
data[index], data[index + gap] = data[index + gap], data[index]
completed = False
Expand Down
1 change: 1 addition & 0 deletions tests/test_sorts.py
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,7 @@ def test_sort_matches_builtin(sort, case):
bubble_sort_recursive,
circle_sort,
cocktail_shaker_sort,
comb_sort,
gnome_sort,
insertion_sort,
merge_sort,
Expand Down
Loading