forked from hariom20singh/python-learning-codes
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpancakeSort.py
More file actions
68 lines (59 loc) · 1.24 KB
/
pancakeSort.py
File metadata and controls
68 lines (59 loc) · 1.24 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# 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)