Algorithms C C++ Tutorials

Program to cyclically rotate an array by one

Given an array, cyclically rotate the array clockwise by one. 

Examples:
Input:  arr[] = {1, 2, 3, 4, 5}
Output: arr[] = {5, 1, 2, 3, 4}

Following are steps for Array Rotation. 

  • Store last element in a variable say x. 
  • Shift all elements one position ahead. 
  • Replace first element of array with x.
#include <stdio.h>

void rotate(int arr[], int n)
{
int x = arr[n-1], i;
for (i = n-1; i > 0; i--)
	arr[i] = arr[i-1];
arr[0] = x;
}

int main()
{
	int arr[] = {1, 2, 3, 4, 5}, i;
	int n = sizeof(arr)/sizeof(arr[0]);

	printf("Given array is\n");
	for (i = 0; i < n; i++)
		printf("%d ", arr[i]);

	rotate(arr, n);

	printf("\nRotated array is\n");
	for (i = 0; i < n; i++)
		printf("%d ", arr[i]);

	return 0;
}

Output

Given array is 
1 2 3 4 5 

Rotated array is
5 1 2 3 4 

Time Complexity: O(n) As we need to iterate through all the elements 
Auxiliary Space: O(1)
The above question can also be solved by using reversal algorithm.

Another approach:

We can use two pointers, say and which point to first and last element of array respectively. As we know in cyclic rotation we will bring last element to first and shift rest in forward direction, so start swaping arr[i] and arr[j] and keep j fixed and i moving towards j.  Repeat till i is not equal to j.

#include <stdio.h>

void swap(int *x, int *y)
{
int temp = *x;
*x = *y;
*y = temp;
}
void rotate(int arr[], int n)
{
int i = 0, j = n - 1;
while(i != j)
{
	swap(&arr[i], &arr[j]);
	i++;
}
}

int main()
{
	int arr[] = {1, 2, 3, 4, 5}, i;
	int n = sizeof(arr)/sizeof(arr[0]);

	printf("Given array is\n");
	for (i = 0; i < n; i++)
		printf("%d ", arr[i]);

	rotate(arr, n);

	printf("\nRotated array is\n");
	for (i = 0; i < n; i++)
		printf("%d ", arr[i]);

	return 0;
}

Output

Given array is 
1 2 3 4 5 
Rotated array is
5 1 2 3 4 
Important Notice for college students

If you’re a college student and have skills in programming languages, Want to earn through blogging? Mail us at geekycomail@gmail.com

For more Programming related blogs Visit Us Geekycodes . Follow us on Instagram.

Leave a Reply

Discover more from Geeky Codes

Subscribe now to keep reading and get access to the full archive.

Continue reading

Discover more from Geeky Codes

Subscribe now to keep reading and get access to the full archive.

Continue reading