Skip to content
Open
Show file tree
Hide file tree
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
30 changes: 20 additions & 10 deletions sorts/power_sort.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,11 +28,15 @@
from __future__ import annotations

from collections.abc import Callable
from typing import Any
from typing import Any, Protocol


def _find_run(
arr: list, start: int, end: int, key: Callable[[Any], Any] | None = None
class Comparable(Protocol):
def __lt__(self, other: Any, /) -> bool: ...


def _find_run[T: Comparable](
arr: list[T], start: int, end: int, key: Callable[[T], Any] | None = None
) -> int:
"""
Detect a run (ascending or descending sequence) starting at 'start'.
Expand Down Expand Up @@ -134,12 +138,12 @@ def _node_power(total_length: int, b1: int, n1: int, b2: int, n2: int) -> int:
return power


def _merge(
arr: list,
def _merge[T: Comparable](
arr: list[T],
start1: int,
end1: int,
end2: int,
key: Callable[[Any], Any] | None = None,
key: Callable[[T], Any] | None = None,
) -> None:
"""
Merge two adjacent sorted runs in-place using auxiliary space.
Expand Down Expand Up @@ -196,12 +200,12 @@ def _merge(
k += 1


def power_sort(
collection: list,
def power_sort[T: Comparable](
collection: list[T],
*,
key: Callable[[Any], Any] | None = None,
key: Callable[[T], Any] | None = None,
reverse: bool = False,
) -> list:
) -> list[T]:
"""
Sort a list using the PowerSort algorithm.

Expand Down Expand Up @@ -257,6 +261,12 @@ def power_sort(
>>> result = power_sort(list(reversed(range(50))))
>>> result == list(range(50))
True
>>> power_sort(["z", "a", "m"]) == sorted(["z", "a", "m"])
True
>>> power_sort([1, "a"])
Traceback (most recent call last):
...
TypeError: '<' not supported between instances of 'str' and 'int'
"""
if len(collection) <= 1:
return collection
Expand Down
3 changes: 3 additions & 0 deletions tests/test_sorts.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@
from sorts.odd_even_transposition_single_threaded import odd_even_transposition
from sorts.pancake_sort import pancake_sort
from sorts.patience_sort import patience_sort
from sorts.power_sort import power_sort
from sorts.quick_sort import quick_sort
from sorts.quick_sort_3_partition import three_way_radix_quicksort
from sorts.recursive_insertion_sort import rec_insertion_sort
Expand Down Expand Up @@ -116,6 +117,7 @@ def test_intro_sort_heap_fallback_preserves_surrounding_items(max_depth: int) ->
odd_even_transposition,
pancake_sort,
patience_sort,
power_sort,
quick_sort,
reverse_selection_sort,
reversort,
Expand Down Expand Up @@ -196,6 +198,7 @@ def test_rec_insertion_sort(case) -> None:
odd_even_transposition,
pancake_sort,
patience_sort,
power_sort,
reverse_selection_sort,
reversort,
selection_sort,
Expand Down