7. Reverse array in groups
Given an array arr[] of positive integers of size N. Reverse every sub-array group of size K.
Example 1:
Input:
N = 5, K = 3
arr[] = {1,2,3,4,5}
Output: 3 2 1 5 4
Explanation: First group consists of elements
1, 2, 3. Second group consists of 4,5.
Example 2:
Input:
N = 4, K = 3
arr[] = {5,6,8,9}
Output: 8 6 5 9
Your Task:
You don't need to read input or print anything. The task is to complete the function reverseInGroups() which takes the array, N and K as input parameters and modifies the array in-place.
Expected Time Complexity: O(N)
Expected Auxiliary Space: O(N)
Constraints:
1 ≤ N, K ≤ 107
1 ≤ A[i] ≤ 1018
// Online C++ compiler to run C++ program online
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
bool is_sorted(int *arr,int n){
if(n==0){
return true;
}
for (int i=0;i<n;i++){
if(arr[i+1]<arr[i]){
return false;
}
}
return true;
}
void rev(int*arr,int n){
for(int i=0;i<n/2;i++){
swap(arr[i],arr[n-1-i]);
}
for (int i=0;i<n;i++){
cout<<arr[i]<<" ";
}
}
void strongest(int *arr,int n){
if(n%2==0){
for(int i=0;i<n-1;i++){
cout<<max(arr[i],arr[i+1])<<" ";
}
}
else{
for(int i=0;i<n;i++){
cout<<max(arr[i],arr[i+1])<<" ";
}
}
}
void rev_grp(int *arr,int n,int k){
int ite=n/k;
//int l=0;
int h=k-1;
for(int i=0;i<=ite;i++){
int l=k*i;
int h=k*i+k-1;
if(h>n-1){
h=n-1;
}
while(l<h){
swap(arr[l],arr[h]);
l++;
h--;
}
}
for (int i=0;i<n;i++){
cout<<arr[i]<<" ";
}
}
int main() {
int cap=5;
int x;
//cin>>x;
int index;
//cin>>index;
int arr[50]={1,2,2,3,4,5,6,7};
//del(arr,9,43);
int arr2[3]={5,5};
rev_grp(arr,8,3);
return 0;
}
Comments
Post a Comment