2017-04-30

Shifting Elements in an Array n time


  • public class ArrayRotation {

  • public static void main(String[] args) {
  • int arr[]={1,2,3};
  • int length=arr.length;
  •                 // change the  rotation/shift value
  • int rotation=2;
  • int toShift=rotation % length;
  • int end=length;
  • int i=0;
  • int arr2[]=new int[length];
  • if(toShift!=0){
  • while(end!=0){
  • if(toShift>=length)
  • toShift=0;
  • arr2[toShift]=arr[i];
  • i++;
  • end--;
  • toShift++;
  • }
  • for(int temp:arr2)
  • System.out.print(temp);
  • }
  • else{
  • for(int temp:arr)
  • System.out.print(temp);
  • }
  • }
  • }



No comments:

Post a Comment