Question:
Reverse an array in groups of a given size
For Example:
Array [1, 2, 3, 4, 5, 6, 7, 8,9,10,11]
Group value =4
Result=4 3 2 1 8 7 6 5 11 10 9
#include <iostream>
using namespace std;
void rev(int arr[], int n, int group_val)
{
for (int i = 0; i < n; i += group_val)
{
int left = i;
int right = min(i + group_val - 1, n - 1);
while (left < right)
swap(arr[left++], arr[right--]);
}
}
int main()
{
int arr[] = {1, 2, 3, 4, 5, 6, 7, 8};
int group_val = 3;
int n = sizeof(arr) / sizeof(arr[0]);
rev(arr, n, group_val);
for (int i = 0; i < n; i++)
cout << arr[i] << " ";
return 0;
}
---------End---------