Skip to content

Commit 94deab7

Browse files
authored
Create pancakeSort.py
1 parent 74b3df0 commit 94deab7

1 file changed

Lines changed: 67 additions & 0 deletions

File tree

Python/Sorting/pancakeSort.py

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
# Python3 program to
2+
# sort array using
3+
# pancake sort
4+
5+
# Reverses arr[0..i] */
6+
def flip(arr, i):
7+
start = 0
8+
while start < i:
9+
temp = arr[start]
10+
arr[start] = arr[i]
11+
arr[i] = temp
12+
start += 1
13+
i -= 1
14+
15+
# Returns index of the maximum
16+
# element in arr[0..n-1] */
17+
def findMax(arr, n):
18+
mi = 0
19+
for i in range(0,n):
20+
if arr[i] > arr[mi]:
21+
mi = i
22+
return mi
23+
24+
# The main function that
25+
# sorts given array
26+
# using flip operations
27+
def pancakeSort(arr, n):
28+
29+
# Start from the complete
30+
# array and one by one
31+
# reduce current size
32+
# by one
33+
curr_size = n
34+
while curr_size > 1:
35+
# Find index of the maximum
36+
# element in
37+
# arr[0..curr_size-1]
38+
mi = findMax(arr, curr_size)
39+
40+
# Move the maximum element
41+
# to end of current array
42+
# if it's not already at
43+
# the end
44+
if mi != curr_size-1:
45+
# To move at the end,
46+
# first move maximum
47+
# number to beginning
48+
flip(arr, mi)
49+
50+
# Now move the maximum
51+
# number to end by
52+
# reversing current array
53+
flip(arr, curr_size-1)
54+
curr_size -= 1
55+
56+
# A utility function to
57+
# print an array of size n
58+
def printArray(arr, n):
59+
for i in range(0,n):
60+
print ("%d"%( arr[i]),end=" ")
61+
62+
# Driver program
63+
arr = [23, 10, 20, 11, 12, 6, 7]
64+
n = len(arr)
65+
pancakeSort(arr, n);
66+
print ("Sorted Array ")
67+
printArray(arr,n)

0 commit comments

Comments
 (0)