C Program for Reversal algorithm for array rotation


An algorithm is a set of instructions that are performed in order to solve the given problem. Here, we will discuss the reversal algorithm for array rotation and create a program for a reversal algorithm.

Now, let's get to some terms that we need to know to solve this problem −

Array − A container of elements of the same data type. The size (number of elements) of the array is fixed at the time of the declaration of the array.

Array rotation − Rotating an array is changing the order of the elements of the array. Increasing the index of the element by one and changing the index of the last element to 0 and so on.

Example of array rotation,

Array[] = {3, 6, 8,1, 4, 10}
Rotated 2 times gives,
Array[] = {4, 10, 3, 6, 8, 1, 4}

Reversal Algorithm

One of the algorithms for array rotation is the reversal algorithm. In this algorithm, subarrays are created and reversed to perform the rotation of the array. Subarrays are created, rotated individually and then joined together and reversed back to get the rotated array.

Algorithm

Input : array arr[] , positions that are needed to be rotated r , length of array n.
Step 1: Split the array into two sub arrays of 0 - (d-1) and d - (n-1) size, a1 [d] and a2[n-d];
Step 2: Reverse both arrays using the reverse method.
Step 3: Join a1 and a2 back to get an array of original size.
Step 4: Reverse this joined array to get the rotated array.
Step 5: Print the array using the standard output method.

Example,

arr[] = {1 ,4, 2, 8, 3, 6, 5}, d = 3, n = 7
a1[]  = {1,4,2} ; a2 = {8,3,6,5}
a1r[] = {2,4,1} // reversed a1
a2r[] = {5,6,3,8} // reversed a2
ar[]  = {2,4,1,5,6,3,8} // a1r+a2r
arr[] = {8,3,6,5,1,4,2} // final answer.

Example

 Live Demo

#include <stdio.h>
void reverse(int arr[], int start, int end){
   int temp;
   while (start < end) {
      temp = arr[start];
      arr[start] = arr[end];
      arr[end] = temp;
      start++;
      end--;
   }
}
int main(){
   int arr[] = { 54, 67, 12, 76, 25, 16, 34 };
   int n = 7;
   int d = 2;
   printf("The initial array is :
");    for (int i = 0; i < n; i++)       printf("%d ", arr[i]);    reverse(arr, 0, d - 1);    reverse(arr, d, n - 1);    reverse(arr, 0, n - 1);    printf("
The left reversed array by %d elements is:
",d);    for (int i = 0; i < n; i++)       printf("%d ", arr[i]);    return 0; }

Output

The initial array is :
54 67 12 76 25 16 34
The left reversed array by 2 elements is:
12 76 25 16 34 54 67

Updated on: 19-Sep-2019

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements