Skip to main content

Posts

Showing posts with the label Reverse Array in Groups

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++: #include<iostream> #include<bits/stdc++.h> using namespace std; void reverseArrayInGroups(long long int *a,int n,int k) {     int t=(n+k-1)/k;     int i=0,j;     stack<long long int> st;     while(t--)     {         j=k;         int l=i;         while(j!=0&&i<n)         {             st.push(a[i]);             i++;             j--;         }         while(!st.empty())         {             a[l]=st.top();             l++;             st.pop();         }     }     for(i=0;i<n;i++)     {         cout<<a[i]<<" ";     }     return; } int main()  { int t; cin>>t; while(t--) {     int n,k;     cin>>n>>k;     long long int a[n];     for(int i=0;i<n;i++)     {         cin>>a[i];     }     reverseArrayInGroups(a,n,k);     cout<&l