Open In App

Pancake Sorting in Python

Last Updated : 27 May, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Pancake Sorting is a sorting algorithm that involves a scenario where you have a stack of pancakes of varying sizes and you want to sort them by size, with the smallest pancake on top and the largest on the bottom. The only operation allowed to sort the pancakes is to insert a spatula at some point in the stack and flip all the pancakes above the spatula. This operation is known as a “prefix reversal” or simply a “flip.”

What is Pancake Sort?

Pancake Sorting works by repeatedly finding the largest unsorted element in the list and flipping it to the top, and then flipping it again to its correct position. The process is repeated for the remaining unsorted portion of the list.

Approach: To solve the problem, follow the below idea:

Unlike a traditional sorting algorithm, which attempts to sort with the fewest comparisons possible, the goal is to sort the sequence in as few reversals as possible. The idea is to do something similar to Selection Sort. We one by one place maximum element at the end and reduce the size of current array by one.

Step-by-step algorithm:

  • Let given array be arr[] and size of array be n.
  • Start from current size equal to n and reduce current size by one while it’s greater than 1. Let the current size be curr_size.
  • Do following for every curr_size
    • Find index of the maximum element in arr[0 to curr_szie-1]. Let the index be ‘mi’
    • Call flip(arr, mi)
    • Call flip(arr, curr_size – 1)

Below is the implementation of the algorithm:

Python
# Python3 program to
# sort array using
# pancake sort

# Reverses arr[0..i] */
def flip(arr, i):
    start = 0
    while start < i:
        temp = arr[start]
        arr[start] = arr[i]
        arr[i] = temp
        start += 1
        i -= 1

# Returns index of the maximum
# element in arr[0..n-1] */
def findMax(arr, n):
    mi = 0
    for i in range(0,n):
        if arr[i] > arr[mi]:
            mi = i
    return mi

# The main function that 
# sorts given array 
# using flip operations
def pancakeSort(arr, n):
    
    # Start from the complete
    # array and one by one
    # reduce current size
    # by one
    curr_size = n
    while curr_size > 1:
        # Find index of the maximum
        # element in 
        # arr[0..curr_size-1]
        mi = findMax(arr, curr_size)

        # Move the maximum element
        # to end of current array
        # if it's not already at 
        # the end
        if mi != curr_size-1:
            # To move at the end, 
            # first move maximum 
            # number to beginning 
            flip(arr, mi)

            # Now move the maximum 
            # number to end by
            # reversing current array
            flip(arr, curr_size-1)
        curr_size -= 1

# A utility function to 
# print an array of size n 
def printArray(arr, n):
    for i in range(0,n):
        print ("%d"%( arr[i]),end=" ")

# Driver program 
arr = [23, 10, 20, 11, 12, 6, 7]
n = len(arr)
pancakeSort(arr, n);
print ("Sorted Array ")
printArray(arr,n)

# This code is contributed by shreyanshi_arun.

Output
Sorted Array 
6 7 10 11 12 20 23 

Time Complexity: O(n2), total O(n) flip operations are performed.
Auxiliary Space: O(1)


Similar Reads

C Program for Pancake sorting
Given an unsorted array, sort the given array. You are allowed to do only following operation on array. flip(arr, i): Reverse array from 0 to i C/C++ Code /* C program for Pancake Sorting */ #include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; /* Reverses arr[0..i] */ void flip(int arr[], int i) { int temp, start = 0; while (start &lt; i) { temp = ar
2 min read
Pancake sorting
Given an unsorted array, the task is to sort the given array. You are allowed to do only following operation on array. flip(arr, i): Reverse array from 0 to i Examples: Input: arr[] = { 23, 10, 20, 11, 12, 6, 7 }Output: { 6, 7, 10, 11, 12, 20, 23} Input: arr[] = { 0, 1, 1, 0, 0 }Output: { 0, 0, 0, 1, 1 } Approach: Unlike a traditional sorting algor
15+ min read
A Pancake Sorting Problem
We have discussed Pancake Sorting in the previous post. Following is a problem based on Pancake Sorting. Given an unsorted array, sort the given array. You are allowed to do only following operation on array. flip(arr, i): Reverse array from 0 to i Imagine a hypothetical machine where flip(i) always takes O(1) time. Write an efficient program for s
15 min read
Sorting objects using In-Place sorting algorithm
Given an array of red, blue and yellow objects, the task is to use an in-place sorting algorithm to sort the array in such a way that all the blue objects appear before all the red objects and all the red objects appear before all the yellow objects.Examples: Input: arr[] = {"blue", "red", "yellow", "blue", "yellow"} Output: blue blue red yellow ye
7 min read
Different ways of sorting Dictionary by Keys and Reverse sorting by keys
Prerequisite: Dictionaries in Python A dictionary is a collection which is unordered, changeable and indexed. In Python, dictionaries are written with curly brackets, and they have keys and values. We can access the values of the dictionary using keys. In this article, we will discuss 10 different ways of sorting the Python dictionary by keys and a
8 min read
What is Sorting in DSA | Sorting meaning
Sorting is defined as the process of arranging a collection of data elements in a specific order, usually in ascending or descending order based on a specific attribute of the data elements. Characteristics of Sorting:Time Complexity: Time complexity, a measure of how long it takes to run an algorithm, is used to categorize sorting algorithms. The
3 min read
Know Your Sorting Algorithm | Set 1 (Sorting Weapons used by Programming Languages)
Ever wondered how sort() function we use in C++/Java or sorted() in Python work internally? Here is a list of all the inbuilt sorting algorithms of different programming languages and the algorithm they use internally. C’s qsort() – QuicksortBest Case Time Complexity- O(NlogN)Average Case Time Complexity- O(NlogN)Worse Case Time Complexity- O(N2)Au
2 min read
What is the stupidest sorting algorithm? (Worst Sorting Algorithm)
Bogo sort stands out as the undisputed champion of stupidity. Unlike other sorting algorithms that follow a structured approach, Bogo sort relies on sheer luck and randomness to achieve its goal. How Bogo Sort Works?Bogo sort operates on the following principle: Randomly shuffle the elements in the list.Check if the list is sorted.If the list is no
2 min read
Different ways of sorting Dictionary by Values and Reverse sorting by values
Prerequisite: Dictionaries in Python A dictionary is a collection which is unordered, changeable, and indexed. In Python, dictionaries are written with curly brackets, and they have keys and values. We can access the values of the dictionary using keys. In this article, 10 different ways of sorting the Python dictionary by values and also reverse s
15+ min read
Python Program To Find Longest Common Prefix Using Sorting
Problem Statement: Given a set of strings, find the longest common prefix.Examples: Input: {"geeksforgeeks", "geeks", "geek", "geezer"} Output: "gee" Input: {"apple", "ape", "april"} Output: "ap" The longest common prefix for an array of strings is the common prefix between 2 most dissimilar strings. For example, in the given array {"apple", "ape",
2 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg