Skip to content

Commit d88f506

Browse files
fix(sorts): prevent comb_sort from returning an unsorted list
1 parent f5988cc commit d88f506

1 file changed

Lines changed: 7 additions & 3 deletions

File tree

sorts/comb_sort.py

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -30,15 +30,19 @@ def comb_sort(data: list) -> list:
3030
[]
3131
>>> comb_sort([99, 45, -7, 8, 2, 0, -15, 3])
3232
[-15, -7, 0, 2, 3, 8, 45, 99]
33+
>>> comb_sort([2, 0, 3, 4, 5, 6, 1])
34+
[0, 1, 2, 3, 4, 5, 6]
3335
"""
3436
shrink_factor = 1.3
3537
gap = len(data)
3638
completed = False
3739

3840
while not completed:
39-
# Update the gap value for a next comb
40-
gap = int(gap / shrink_factor)
41-
if gap <= 1:
41+
# Update the gap value for a next comb. The gap is never allowed to drop
42+
# below 1: a gap of 0 compares each element with itself, so no swap can
43+
# ever happen and the loop would exit while the data is still unsorted.
44+
gap = max(int(gap / shrink_factor), 1)
45+
if gap == 1:
4246
completed = True
4347

4448
index = 0

0 commit comments

Comments
 (0)