Tuesday, 14 March 2017

Rotate an array to the right by a given number of steps


Given an list of integers of Strings.We need to rotate the list in right direction.
There are few approaches to accomplish the Solution:

  • We can use two for loops and rotate the elements one by one.
  • We can use Collections utility class rotate method.


Sample Program:

import java.util.ArrayList;  
 import java.util.Collections;  
 import java.util.List;  
 /**  
  *   
  */  
 /**  
  * @author Dixit  
  *  
  */  
 public class RotateElement {  
      /**  
       * @param args  
       */  
      public static void main(String[] args) {  
           List<String> list = new ArrayList<String>();  
           list.add("1");  
           list.add("2");  
           list.add("3");  
           list.add("4");  
           list.add("5");  
           list.add("6");  
           System.out.println("Before Rotating :" + list);  
           Collections.rotate(list, 2);  
           System.out.println("After Rotating :" + list);  
      }  
 }  


Output:

 Before Rotating :[1, 2, 3, 4, 5, 6]  
 After Rotating :[5, 6, 1, 2, 3, 4]  

Enjoy Learning.

No comments:

Post a Comment