Skip to content

Instantly share code, notes, and snippets.

@iyashjayesh
Created July 18, 2020 07:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save iyashjayesh/1fada4a0354e102336169eef2b81c091 to your computer and use it in GitHub Desktop.
Save iyashjayesh/1fada4a0354e102336169eef2b81c091 to your computer and use it in GitHub Desktop.
One by One rotation of Array - Time Complexity O(n*d)
// C++ program to rotate an array by d elements
#include <bits/stdc++.h>
using namespace std;
/*Function to left Rotate arr[] of size n by 1*/
void leftRotatebyOne(int arr[], int n)
{
int temp = arr[0], i;
for (i = 0; i < n - 1; i++)
arr[i] = arr[i + 1];
arr[i] = temp;
}
/*Function to left rotate arr[] of size n by d*/
void rotate(int arr[], int d, int n)
{
for (int i = 0; i < d; i++)
leftRotatebyOne(arr, n);
}
/* Driver program to test above functions */
int main()
{
//ios_base::sync_with_stdio(0), cin.tie(0), cout.tie(0);
int n;
cin >> n;
int a[n];
for (int i = 0; i < n; i++)
cin>>a[i];
int d;
//number of rotations
cin >>d;
//Rotating the array
rotate(a,d,n);
//Printing out the array
for (int i = 0; i < n; i++)
cout <<a[i] <<" ";
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment