Rotate array Elements

How to you a write a function to rotate elements of a an array by n places.

  • Save last element of array in temp
  • Copy a[i-1] to a[i] for all i from len-1 to 1.
              for(i=len-1;i>0;i--)
                 a[i] = a[i-1];

  • Copy temp to a[0]
  • Repeat these 3 steps n number of times
 void rotoateElements(int arr[],int len,int nbits)  
 {  
    int i,j;  
    for(j=0;j<nbits;j++)  
    {  
      int temp=a[len-1]; //Save last element  
      for(i=len-1;i>0;i--)  
      {  
         a[i]=a[i-1];//shift each element by one place  
       }  
      a[0] = temp;//copy last element to 0th element  
     }  
  }  

Comments

Popular Posts