Skip to content

Commit d2921ce

Browse files
author
berlin880
committed
fix(sorts): support comparable items in pancake sort
1 parent d740bb0 commit d2921ce

1 file changed

Lines changed: 23 additions & 10 deletions

File tree

sorts/pancake_sort.py

Lines changed: 23 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
# sorts/pancake_sort.py
12
"""
23
This is a pure Python implementation of the pancake sort algorithm
34
For doctests run following command:
@@ -14,37 +15,49 @@
1415
T = TypeVar("T")
1516

1617

17-
def pancake_sort[T](arr: Sequence[T]) -> list[T]:
18+
def pancake_sort(arr: Sequence[T]) -> list[T]:
1819
"""Sort Array with Pancake Sort.
20+
1921
:param arr: Collection containing comparable items
2022
:return: Collection ordered in ascending order of items
23+
2124
Examples:
2225
>>> pancake_sort([0, 5, 3, 2, 2])
2326
[0, 2, 2, 3, 5]
2427
>>> pancake_sort([])
2528
[]
2629
>>> pancake_sort([-2, -5, -45])
2730
[-45, -5, -2]
31+
>>> pancake_sort(["banana", "apple", "orange"])
32+
['apple', 'banana', 'orange']
2833
29-
Time Complexity: (O(n^2))
30-
Space Complexity: (O(n))
34+
Time Complexity: O(n^2)
35+
Space Complexity: O(n)
3136
"""
3237
cur = len(arr)
38+
3339
while cur > 1:
34-
# Find the maximum number in arr
35-
mi = arr.index(max(arr[0:cur]))
36-
# Reverse from 0 to mi
37-
arr = arr[mi::-1] + arr[mi + 1 : len(arr)]
38-
# Reverse whole list
39-
arr = arr[cur - 1 :: -1] + arr[cur : len(arr)]
40+
# Find the maximum item in the unsorted portion.
41+
maximum = max(arr[:cur])
42+
mi = arr.index(maximum)
43+
44+
# Move the maximum item to the front.
45+
arr = arr[mi::-1] + arr[mi + 1 :]
46+
47+
# Move the maximum item to its final position.
48+
arr = arr[cur - 1 :: -1] + arr[cur:]
49+
4050
cur -= 1
41-
return arr
51+
52+
return list(arr)
4253

4354

4455
if __name__ == "__main__":
4556
import doctest
4657

4758
doctest.testmod()
59+
4860
user_input = input("Enter numbers separated by a comma:\n").strip()
4961
unsorted = [int(item) for item in user_input.split(",")]
5062
print(f"{pancake_sort(unsorted) = }")
63+

0 commit comments

Comments
 (0)