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);
  • }
  • }
  • }



Comments

Popular posts from this blog

Today Walkin 14th-Sept

Hibernate Search - Elasticsearch with JSON manipulation

Spring Elasticsearch Operations