Skip to content
Related Articles

Related Articles

Javascript Program for Program to cyclically rotate an array by one

Improve Article
Save Article
Like Article
  • Difficulty Level : Medium
  • Last Updated : 26 Dec, 2021

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. 
1) Store last element in a variable say x. 
2) Shift all elements one position ahead. 
3) Replace first element of array with x.
 

Javascript




<script>
  
// JavaScript code for program 
// to cyclically rotate
// an array by one
function rotate(arr, n)
{
  var x = arr[n-1], i;
  for(i = n-1; i > 0; i--)
      arr[i] = arr[i-1];
  arr[0] = x;    
}
  
var arr = [1, 2, 3, 4, 5];
var n = arr.length;
  
document.write("Given array is <br>");
for(var i = 0; i< n; i++)
    document.write(arr[i] + " ");
      
rotate(arr, n);
  
document.write("<br>Rotated array is <br>");
for(var i = 0; i < n; i++)
    document.write(arr[i] + " ");
      
</script>
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 i and j 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.

Javascript




<script>
// JavaScript code for program
// to cyclically rotate
// an array by one using pointers i,j
  
function rotate(arr, n){
    var i = 0
    var j = n-1
    while(i != j){
        let temp;
  
        temp = arr[i];
        arr[i] = arr[j];
        arr[j]= temp;
        i =i+1
    }
}
  
var arr = [1, 2, 3, 4, 5];
var n = arr.length;
  
document.write("Given array is <br>");
for(var i = 0; i< n; i++)
    document.write(arr[i] + " ");
      
rotate(arr, n);
  
document.write("<br>Rotated array is <br>");
for(var i = 0; i < n; i++)
    document.write(arr[i] + " ");
</script>
Output
Given array is 
1 2 3 4 5 
Rotated array is
5 1 2 3 4 

Please refer complete article on Program to cyclically rotate an array by one for more details!


My Personal Notes arrow_drop_up

Start Your Coding Journey Now!