|
| 1 | +# sorts/pancake_sort.py |
1 | 2 | """ |
2 | 3 | This is a pure Python implementation of the pancake sort algorithm |
3 | 4 | For doctests run following command: |
|
14 | 15 | T = TypeVar("T") |
15 | 16 |
|
16 | 17 |
|
17 | | -def pancake_sort[T](arr: Sequence[T]) -> list[T]: |
| 18 | +def pancake_sort(arr: Sequence[T]) -> list[T]: |
18 | 19 | """Sort Array with Pancake Sort. |
| 20 | +
|
19 | 21 | :param arr: Collection containing comparable items |
20 | 22 | :return: Collection ordered in ascending order of items |
| 23 | +
|
21 | 24 | Examples: |
22 | 25 | >>> pancake_sort([0, 5, 3, 2, 2]) |
23 | 26 | [0, 2, 2, 3, 5] |
24 | 27 | >>> pancake_sort([]) |
25 | 28 | [] |
26 | 29 | >>> pancake_sort([-2, -5, -45]) |
27 | 30 | [-45, -5, -2] |
| 31 | + >>> pancake_sort(["banana", "apple", "orange"]) |
| 32 | + ['apple', 'banana', 'orange'] |
28 | 33 |
|
29 | | - Time Complexity: (O(n^2)) |
30 | | - Space Complexity: (O(n)) |
| 34 | + Time Complexity: O(n^2) |
| 35 | + Space Complexity: O(n) |
31 | 36 | """ |
32 | 37 | cur = len(arr) |
| 38 | + |
33 | 39 | 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 | + |
40 | 50 | cur -= 1 |
41 | | - return arr |
| 51 | + |
| 52 | + return list(arr) |
42 | 53 |
|
43 | 54 |
|
44 | 55 | if __name__ == "__main__": |
45 | 56 | import doctest |
46 | 57 |
|
47 | 58 | doctest.testmod() |
| 59 | + |
48 | 60 | user_input = input("Enter numbers separated by a comma:\n").strip() |
49 | 61 | unsorted = [int(item) for item in user_input.split(",")] |
50 | 62 | print(f"{pancake_sort(unsorted) = }") |
| 63 | + |
0 commit comments