Дано целочисленный массив из n элементов. Проверить, если массив является симметричным, то в каждой из его половин изменить порядок элементов на обратный. В противном случае его половины поменять местами. С++
#include <iostream> #include <vector> void reverseArray(std::vector<int>& arr, int start, int end) { while (start < end) { int temp = arr[start]; arr[start] = arr[end]; arr[end] = temp; start++; end--; } } void swapHalves(std::vector<int>& arr, int n) { int mid = n / 2; if (n % 2 == 0) { reverseArray(arr, 0, mid - 1); reverseArray(arr, mid, n - 1); } else { reverseArray(arr, 0, mid - 1); reverseArray(arr, mid + 1, n - 1); reverseArray(arr, 0, n - 1); } } int main() { int n; std::cout << "Enter the number of elements in the array: "; std::cin >> n; std::vector<int> arr(n); std::cout << "Enter the elements of the array: "; for (int i = 0; i < n; i++) { std::cin >> arr[i]; } if (n % 2 == 0) { bool isSymmetric = true; for (int i = 0; i < n / 2; i++) { if (arr[i] != arr[n - i - 1]) { isSymmetric = false; break; } } if (isSymmetric) { swapHalves(arr, n); } else { reverseArray(arr, 0, n / 2 - 1); reverseArray(arr, n / 2, n - 1); } } else { swapHalves(arr, n); } std::cout << "Modified array:"; for (int i = 0; i < n; i++) { std::cout << " " << arr[i]; } std::cout << std::endl; return 0; }
Пример работы программы:
Enter the number of elements in the array: 6 Enter the elements of the array: 1 2 3 3 2 1 Modified array: 3 2 1 1 2 3 Enter the number of elements in the array: 5 Enter the elements of the array: 1 2 3 4 5 Modified array: 3 2 1 5 4
#include <vector>
void reverseArray(std::vector<int>& arr, int start, int end) {
while (start < end) {
int temp = arr[start];
arr[start] = arr[end];
arr[end] = temp;
start++;
end--;
}
}
void swapHalves(std::vector<int>& arr, int n) {
int mid = n / 2;
if (n % 2 == 0) {
reverseArray(arr, 0, mid - 1);
reverseArray(arr, mid, n - 1);
} else {
reverseArray(arr, 0, mid - 1);
reverseArray(arr, mid + 1, n - 1);
reverseArray(arr, 0, n - 1);
}
}
int main() {
int n;
std::cout << "Enter the number of elements in the array: ";
std::cin >> n;
std::vector<int> arr(n);
std::cout << "Enter the elements of the array: ";
for (int i = 0; i < n; i++) {
std::cin >> arr[i];
}
if (n % 2 == 0) {
bool isSymmetric = true;
for (int i = 0; i < n / 2; i++) {
if (arr[i] != arr[n - i - 1]) {
isSymmetric = false;
break;
}
}
if (isSymmetric) {
swapHalves(arr, n);
} else {
reverseArray(arr, 0, n / 2 - 1);
reverseArray(arr, n / 2, n - 1);
}
} else {
swapHalves(arr, n);
}
std::cout << "Modified array:";
for (int i = 0; i < n; i++) {
std::cout << " " << arr[i];
}
std::cout << std::endl;
return 0;
}
Пример работы программы:
Enter the number of elements in the array: 6Enter the elements of the array: 1 2 3 3 2 1
Modified array: 3 2 1 1 2 3
Enter the number of elements in the array: 5
Enter the elements of the array: 1 2 3 4 5
Modified array: 3 2 1 5 4