-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPancakeSorting.cpp
113 lines (101 loc) · 1.44 KB
/
PancakeSorting.cpp
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
#include<iostream>
#include<bits/stdc++.h>
using namespace std;
/*
Problem reference LeetCode - 969
if we can somehow place max(0..n) at n
so the problem resolves to max(0..n-1) at n-1
so on
Until the whole array would become sorted.
*/
class Solution
{
vector<int> arr;
public:
Solution()
{
}
void fillArray(int temp)
{
arr.push_back(temp);
}
void swap(int* x, int* y)
{
int temp = *x;
*x = *y;
*y = temp;
}
void flipOperation(int k)
{
int i = 0;
int j = 0 + k - 1;
while (i < j)
{
swap(&arr[i], &arr[j]);
++i;
--j;
}
}
int findMaxIndex(int high)
{
int maxr = INT_MIN;
int max_index = -1;
for (int i = 0; i <= high; i++)
{
if (arr[i] > maxr)
{
maxr = arr[i];
max_index = i;
}
}
return max_index;
}
vector<int> pancakeSort()
{
vector<int> temp;
int n = arr.size() - 1;
while (n >= 0)
{
int idx = findMaxIndex(n);
if(n!=idx)
{
temp.push_back(idx+1);
}
flipOperation(idx + 1);
flipOperation(n + 1);
if(n!=idx)
{
temp.push_back(n+1);
}
n--;
}
return temp;
}
void printArray(vector<int>& arr)
{
for(auto it:arr)
{
cout << it << " ";
}
cout << endl;
}
};
int main()
{
int test_cases;
cin >> test_cases;
while (test_cases--)
{
Solution s;
int n;
cin >> n;
for (int i = 0; i < n; i++)
{
int temp ;
cin >> temp;
s.fillArray(temp);
}
vector<int> temp = s.pancakeSort();
s.printArray(temp);
}
}