Skip to content
Merged
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
36 changes: 28 additions & 8 deletions sorts/pancake_sort.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
"""
This is a pure Python implementation of the pancake sort algorithm

For doctests run following command:
python3 -m doctest -v pancake_sort.py
or
Expand All @@ -9,26 +10,45 @@
"""

from collections.abc import Sequence
from typing import TypeVar
from typing import Any, Protocol, TypeVar


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

T = TypeVar("T")

T = TypeVar("T", bound=Comparable)

def pancake_sort[T](arr: Sequence[T]) -> list[T]:

def pancake_sort[T: Comparable](arr: Sequence[T]) -> list[T]:
"""Sort Array with Pancake Sort.
:param arr: Collection containing comparable items
:return: Collection ordered in ascending order of items

:param arr: some ordered collection with heterogeneous comparable items
inside
:return: the same collection ordered by ascending

Time Complexity: (O(n^2))
Space Complexity: (O(n))

Examples:
>>> pancake_sort([0, 5, 3, 2, 2])
[0, 2, 2, 3, 5]
>>> pancake_sort([])
[]
>>> pancake_sort([-2, -5, -45])
[-45, -5, -2]

Time Complexity: (O(n^2))
Space Complexity: (O(n))
>>> pancake_sort(['d', 'a', 'b', 'e', 'c']) == sorted(['d', 'a', 'b', 'e', 'c'])
True
>>> import random
>>> collection = random.sample(range(-50, 50), 100)
>>> pancake_sort(collection) == sorted(collection)
True
>>> import string
>>> collection = random.choices(string.ascii_letters + string.digits, k=100)
>>> pancake_sort(collection) == sorted(collection)
True
"""
arr = list(arr)
cur = len(arr)
while cur > 1:
# Find the maximum number in arr
Expand Down
3 changes: 3 additions & 0 deletions tests/test_sorts.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@
from sorts.iterative_merge_sort import iter_merge_sort
from sorts.merge_sort import merge_sort
from sorts.odd_even_sort import odd_even_sort
from sorts.pancake_sort import pancake_sort
from sorts.patience_sort import patience_sort
from sorts.quick_sort import quick_sort
from sorts.selection_sort import selection_sort
Expand Down Expand Up @@ -65,6 +66,7 @@ def test_heap_sort() -> None:
iter_merge_sort,
merge_sort,
odd_even_sort,
pancake_sort,
patience_sort,
quick_sort,
selection_sort,
Expand Down Expand Up @@ -124,6 +126,7 @@ def test_sort_matches_builtin(sort, case) -> None:
gnome_sort,
insertion_sort,
merge_sort,
pancake_sort,
selection_sort,
shrink_shell_sort,
],
Expand Down
Loading