Rotate the given array in cycles

Objective: Given an array of integers, write a program to rotate the array in cyclic manner by one.

Example:

Int a [] = {1, 2, 3, 4, 5}
Output:  {2, 3, 4, 5, 1}

Approach:

  • Store the first element of array in temporary variable.
  • From 2nd element to last element, left shift all the elements by one position.
  • Put the temporary variable value at the last index of the array.
  • See the image below for better understanding.


 Java Code:



Output:

Original Array: [1, 2, 3, 4, 5]
Rotated Array: [2, 3, 4, 5, 1]
__________________________
Original Array: [2, 3, 4, 5, 1]
Rotated Array: [3, 4, 5, 1, 2]

__________________________________________________
Top Companies Interview Questions..-

Google Microsoft Amazon Facebook more..

If you find anything incorrect or you feel that there is any better approach to solve the above problem, please write comment.
__________________________________________________

%d bloggers like this: