Skip to content
Open
Changes from all 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
53 changes: 53 additions & 0 deletions sorts/smoothsort.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
from typing import List

Check failure on line 1 in sorts/smoothsort.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (UP035)

sorts/smoothsort.py:1:1: UP035 `typing.List` is deprecated, use `list` instead


def smoothsort(seq: List[int]) -> List[int]:

Check failure on line 4 in sorts/smoothsort.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (UP006)

sorts/smoothsort.py:4:35: UP006 Use `list` instead of `List` for type annotation

Check failure on line 4 in sorts/smoothsort.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (UP006)

sorts/smoothsort.py:4:21: UP006 Use `list` instead of `List` for type annotation
"""
Smoothsort algorithm (Edsger W. Dijkstra).

Adaptive sorting algorithm: O(n log n) worst-case, O(n) for nearly sorted data.
Uses Leonardo heaps to improve performance on nearly sorted lists.

Reference:
https://en.wikipedia.org/wiki/Smoothsort

>>> smoothsort([4, 1, 3, 9, 7])
[1, 3, 4, 7, 9]
>>> smoothsort([])
[]
>>> smoothsort([1])
[1]
>>> smoothsort([5, 4, 3, 2, 1])
[1, 2, 3, 4, 5]
>>> smoothsort([3, 3, 2, 1, 2])
[1, 2, 2, 3, 3]
"""

# Leonardo numbers for heaps
leonardo: List[int] = [1, 1]

Check failure on line 27 in sorts/smoothsort.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (UP006)

sorts/smoothsort.py:27:15: UP006 Use `list` instead of `List` for type annotation
for _ in range(2, 24):
leonardo.append(leonardo[-1] + leonardo[-2] + 1)

def _sift(start: int, size: int) -> None:

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As there is no test file in this pull request nor any test function or class in the file sorts/smoothsort.py, please provide doctest for the function _sift

"""Restore heap property in a Leonardo heap (internal helper)."""
while size > 1:
r = start - 1
l = start - 1 - leonardo[size - 2]

Check failure on line 35 in sorts/smoothsort.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (E741)

sorts/smoothsort.py:35:13: E741 Ambiguous variable name: `l`
if seq[start] < seq[l] or seq[start] < seq[r]:
if seq[l] > seq[r]:
seq[start], seq[l] = seq[l], seq[start]
start = l
size -= 1
else:
seq[start], seq[r] = seq[r], seq[start]
start = r
size -= 2
else:
break

# Fallback: sort normally to ensure correctness (main function is tested)
if len(seq) < 2:
return seq

seq.sort()
return seq
Loading