diff --git a/sorts/pancake_sort.py b/sorts/pancake_sort.py index 861190e01d18..50eb8cc783f3 100644 --- a/sorts/pancake_sort.py +++ b/sorts/pancake_sort.py @@ -1,12 +1,23 @@ -""" -This is a pure Python implementation of the pancake sort algorithm +"""Pancake Sort Algorithm Implementation. + +A pure Python implementation of the Pancake Sort algorithm. +Pancake sort is a sorting algorithm that sorts an array by repeatedly flipping +subsections of the array, similar to how you might sort a stack of pancakes +by inserting a spatula and flipping the top portion. + +The algorithm works by finding the maximum element, flipping it to the top, +then flipping it down to its correct position. This process is repeated for +the remaining unsorted portion. + +Time Complexity: O(n^2) - We perform n iterations, each with up to 2 flips +Space Complexity: O(1) - In-place sorting, only uses a constant amount of extra space For doctests run following command: -python3 -m doctest -v pancake_sort.py + python3 -m doctest -v pancake_sort.py or -python -m doctest -v pancake_sort.py + python -m doctest -v pancake_sort.py For manual testing run: -python pancake_sort.py + python pancake_sort.py """ from collections.abc import Sequence @@ -51,12 +62,13 @@ def pancake_sort[T: Comparable](arr: Sequence[T]) -> list[T]: arr = list(arr) 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 index of maximum element in arr[0:cur] + max_index = arr.index(max(arr[:cur])) + # Move maximum element to end of current unsorted portion: + # 1. Flip to bring max to the beginning + arr[: max_index + 1] = reversed(arr[: max_index + 1]) + # 2. Flip to send max to position cur-1 + arr[:cur] = reversed(arr[:cur]) cur -= 1 return arr @@ -67,4 +79,4 @@ def pancake_sort[T: Comparable](arr: Sequence[T]) -> list[T]: 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) = }") + print(f"{unsorted = }, {pancake_sort(unsorted) = }")