How to rotate an array by d elements? (Efficient approach)
#include <bits/stdc++.h>
using namespace std;
void reverseArray(int a[],int i,int j)
{
while(i<j)
{
swap(a[i],a[j]);
i++;
j--;
}
}
int main()
{
int n,d;
cin>>n>>d;
int a[n];
for(int i=0;i<n;i++)
cin>>a[i];
reverseArray(a,0,d-1);
reverseArray(a,d,n-1);
reverseArray(a,0,n-1);
for(int i=0;i<n;i++)
cout<<a[i]<<" ";
return 0;
}
10 3
1 2 3 4 5 6 7 8 9 10
0 Comments