Skip to main content

Reverse Array in Groups

Task: Given an array arr[] of size N. Reverse every sub array of K elements.

Example:
Input:
1
5 3
1 2 3 4 5
Output:
3 2 1 5 4

Here is the Code:
Program in C++:

  1. #include<iostream>
  2. #include<bits/stdc++.h>
  3. using namespace std;
  4. void reverseArrayInGroups(long long int *a,int n,int k)
  5. {
  6.     int t=(n+k-1)/k;
  7.     int i=0,j;
  8.     stack<long long int> st;
  9.     while(t--)
  10.     {
  11.         j=k;
  12.         int l=i;
  13.         while(j!=0&&i<n)
  14.         {
  15.             st.push(a[i]);
  16.             i++;
  17.             j--;
  18.         }
  19.         while(!st.empty())
  20.         {
  21.             a[l]=st.top();
  22.             l++;
  23.             st.pop();
  24.         }
  25.     }
  26.     for(i=0;i<n;i++)
  27.     {
  28.         cout<<a[i]<<" ";
  29.     }
  30.     return;
  31. }
  32. int main()
  33.  {
  34. int t;
  35. cin>>t;
  36. while(t--)
  37. {
  38.     int n,k;
  39.     cin>>n>>k;
  40.     long long int a[n];
  41.     for(int i=0;i<n;i++)
  42.     {
  43.         cin>>a[i];
  44.     }
  45.     reverseArrayInGroups(a,n,k);
  46.     cout<<endl;
  47. }
  48. return 0;
  49. }

Here is the Video: