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
|
#include <iostream>
void print(int *arr, size_t sz) {
for (size_t i = 0; i < sz; i++)
std::cout << arr[i] << ' ';
std::cout << '\n';
}
bool sorted(int arr[], size_t sz) {
for (size_t i = 1; i < sz; i++)
if (arr[i - 1] > arr[i])
return false;
return true;
}
size_t find_index_of_max(int *a, size_t sz) {
size_t m = 0;
for (size_t i = 1; i < sz; i++)
if (a[i] > a[m])
m = i;
return m;
}
void flip(int *a, size_t m) {
for (size_t i = 0; i <= m / 2; i++) {
int t = a[i]; a[i] = a[m - i]; a[m - i] = t;
}
}
void pancake(int arr[], size_t sz) {
while (sz > 1) {
size_t m = find_index_of_max(arr, sz);
if (m < --sz) { // if maximum is not already at the bottom
flip(arr, m); // flip it to the top
flip(arr, sz); // then flip it to the bottom
}
}
}
int main() {
int arr[] = { 15,1,6,10,20,25,30,53,11,7,34,12,76,43,37 };
size_t sz = sizeof arr / sizeof arr[0];
print(arr, sz);
pancake(arr, sz);
print(arr, sz);
}
|