Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to rotate an array right

I have wrote a program to shift an int array left, but cannot find a way to move it right. Could you take a look at my code and comment if you have any ideas how how to "rotate" my array right based on the number of spaces (int x), as currently it only moves left. Thanks

public void makeRight(int x) {
   int[] anArray = {0, 1, 2, 3, 4, 5};
   int counter = 0;
   while (counter < x) {
        int temp = anArray[0];
        for (int i = 0; i < anArray.length - 1; i++) {
            anArray[i] = anArray[i + 1];
         }

         anArray[anArray.length - 1] = temp;
         counter++;
  }
  for (int i = 0; i < anArray.length; i++){
      System.out.print(anArray[i] + " ");
  }
}
like image 496
Joe John Avatar asked Feb 03 '16 06:02

Joe John


1 Answers

Rotate an array right

public void makeRight( int x )
{
    int[] anArray =
    { 0, 1, 2, 3, 4, 5 };
    int counter = 0;
    while ( counter < x )
    {
        int temp = anArray[anArray.length - 1];
        for ( int i = anArray.length - 1; i > 0; i-- )
        {
            anArray[i] = anArray[i - 1];
        }
        anArray[0] = temp;
        counter++;
    }
    for ( int i = 0; i < anArray.length; i++ )
    {
        System.out.print( anArray[i] + " " );
    }
}
like image 89
Anand Pandey Avatar answered Sep 18 '22 14:09

Anand Pandey