Skip to content
Closed
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
29 changes: 25 additions & 4 deletions sorts/reverse_selection.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,23 @@
This algorithm progressively sorts the array by reversing subarrays

For doctests run following command:
python3 -m doctest -v reverse_selection_sort.py
python3 -m doctest -v reverse_selection.py

For manual testing run:
python3 reverse_selection_sort.py
python3 reverse_selection.py
"""

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

def reverse_subarray(arr: list, start: int, end: int) -> None:

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


def reverse_subarray[T: Comparable](
arr: MutableSequence[T], start: int, end: int
) -> None:
"""
Reverse a subarray in-place.

Expand Down Expand Up @@ -41,7 +50,9 @@ def reverse_subarray(arr: list, start: int, end: int) -> None:
end -= 1


def reverse_selection_sort(collection: list) -> list:
def reverse_selection_sort[T: Comparable](
collection: MutableSequence[T],
) -> MutableSequence[T]:
"""
A pure implementation of reverse selection sort algorithm in Python

Expand All @@ -64,6 +75,16 @@ def reverse_selection_sort(collection: list) -> list:

>>> reverse_selection_sort([5, 4, 3, 2, 1])
[1, 2, 3, 4, 5]

>>> reverse_selection_sort(["c", "a", "b"])
['a', 'b', 'c']

>>> reverse_selection_sort([2.5, -1, 0.0])
[-1, 0.0, 2.5]

>>> reverse_selection_sort([1, "a"])
Traceback (most recent call last):
TypeError: '<' not supported between instances of 'str' and 'int'
"""
n = len(collection)
for i in range(n - 1):
Expand Down
3 changes: 3 additions & 0 deletions tests/test_sorts.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@
from sorts.odd_even_sort import odd_even_sort
from sorts.patience_sort import patience_sort
from sorts.quick_sort import quick_sort
from sorts.reverse_selection import reverse_selection_sort
from sorts.selection_sort import selection_sort
from sorts.shell_sort import shell_sort
from sorts.stooge_sort import stooge_sort
Expand Down Expand Up @@ -66,6 +67,7 @@ def test_heap_sort() -> None:
odd_even_sort,
patience_sort,
quick_sort,
reverse_selection_sort,
selection_sort,
shell_sort,
stooge_sort,
Expand Down Expand Up @@ -121,6 +123,7 @@ def test_sort_matches_builtin(sort, case) -> None:
gnome_sort,
insertion_sort,
merge_sort,
reverse_selection_sort,
selection_sort,
],
ids=lambda f: f.__name__,
Expand Down
Loading