8000 Merge pull request #1151 from vidz-1/patch-6 · oo7dotcom/Algorithms@e49b528 · GitHub
[go: up one dir, main page]

Skip to content

Commit e49b528

Browse files
authored
Merge pull request VAR-solutions#1151 from vidz-1/patch-6
Create C++
2 parents a64d00e + 1c4a197 commit e49b528

File tree

1 file changed

+91
-0
lines changed

1 file changed

+91
-0
lines changed
Lines changed: 91 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,91 @@
1+
// C++ program to
2+
// sort array using
3+
// pancake sort
4+
#include<bits/stdc++.h>
5+
using namespace std;
6+
7+
/* Reverses arr[0..i] */
8+
void flip(int arr[], int i)
9+
{
10+
int temp, start = 0;
11+
while (start < i)
12+
{
13+
temp = arr[start];
14+
arr[start] = arr[i];
15+
arr[i] = temp;
16+
start++;
17+
i--;
18+
}
19+
}
20+
21+
// Returns index of the
22+
// maximum element in
23+
// arr[0..n-1]
24+
int findMax(int arr[], int n)
25+
{
26+
int mi, i;
27+
for (mi = 0, i = 0; i < n; ++i)
28+
if (arr[i] > arr[mi])
29+
mi = i;
30+
return mi;
31+
}
32+
33+
// The main function that
34+
// sorts given array using
35+
// flip operations
36+
int pancakeSort(int *arr, int n)
37+
{
38+
// Start from the complete
39+
// array and one by one
40+
// reduce current size 10000
41+
// by one
42+
for (int curr_size = n; curr_size > 1; --curr_size)
43+
{
44+
// Find index of the
45+
// maximum element in
46+
// arr[0..curr_size-1]
47+
int mi = findMax(arr, curr_size);
48+
49+
// Move the maximum
50+
// element to end of
51+
// current array if
52+
// it's not already
53+
// at the end
54+
if (mi != curr_size-1)
55+
{
56+
// To move at the end,
57+
// first move maximum
58+
// number to beginning
59+
flip(arr, mi);
60+
61+
// Now move the maximum
62+
// number to end by
63+
// reversing current array
64+
flip(arr, curr_size-1);
65+
}
66+
}
67+
}
68+
69+
// A utility function to print
70+
// n array of size n
71+
void printArray(int arr[], int n)
72+
{
73+
for (int i = 0; i < n; ++i)
74+
cout<< arr[i]<<" ";
75+
}
76+
77+
// Driver program to test above function
78+
int main()
79+
{
80+
int arr[] = {23, 10, 20, 11, 12, 6, 7};
81+
int n = sizeof(arr)/sizeof(arr[0]);
82+
83+
pancakeSort(arr, n);
84+
85+
cout<<"Sorted Array "<<endl;
86+
printArray(arr, n);
87+
88+
return 0;
89+
}
90+
91+
//This code is contributed by vidz-1

0 commit comments

Comments
 (0)
0