Skip to content
Closed
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
32 changes: 22 additions & 10 deletions sorts/pancake_sort.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
# sorts/pancake_sort.py
"""
This is a pure Python implementation of the pancake sort algorithm
For doctests run following command:
Expand All @@ -14,37 +15,48 @@
T = TypeVar("T")


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

Check failure on line 18 in sorts/pancake_sort.py

View workflow job for this annotation

GitHub Actions / ruff

ruff (UP047)

sorts/pancake_sort.py:18:5: UP047 Generic function `pancake_sort` should use type parameters help: Use type parameters
"""Sort Array with Pancake Sort.

:param arr: Collection containing comparable items
:return: Collection ordered in ascending order of items

Examples:
>>> pancake_sort([0, 5, 3, 2, 2])
[0, 2, 2, 3, 5]
>>> pancake_sort([])
[]
>>> pancake_sort([-2, -5, -45])
[-45, -5, -2]
>>> pancake_sort(["banana", "apple", "orange"])
['apple', 'banana', 'orange']

Time Complexity: (O(n^2))
Space Complexity: (O(n))
Time Complexity: O(n^2)
Space Complexity: O(n)
"""
cur = len(arr)

while cur > 1:
# Find the maximum number in arr
mi = arr.index(max(arr[0:cur]))
# Reverse from 0 to mi
arr = arr[mi::-1] + arr[mi + 1 : len(arr)]
# Reverse whole list
arr = arr[cur - 1 :: -1] + arr[cur : len(arr)]
# Find the maximum item in the unsorted portion.
maximum = max(arr[:cur])
mi = arr.index(maximum)

# Move the maximum item to the front.
arr = arr[mi::-1] + arr[mi + 1 :]

# Move the maximum item to its final position.
arr = arr[cur - 1 :: -1] + arr[cur:]

cur -= 1
return arr

return list(arr)


if __name__ == "__main__":
import doctest

doctest.testmod()

user_input = input("Enter numbers separated by a comma:\n").strip()
unsorted = [int(item) for item in user_input.split(",")]
print(f"{pancake_sort(unsorted) = }")
Loading