guarrana
guarrana

Reputation: 79

Shifting all elements of an array back one in Java

I am writing a code that will shift all elements of an array back one, and move the last element to the front of the array.

I pretty much want my program to do this:

int[] array = new int[] {1, 2, 3};
// do something such that array will become {3, 1, 2}

My code is as follows:

int[] array = new int[3];


for(int i = 0; i < array.length; i++)
{
  array[0] = 1;
  array[1] = 2;
  array[2] = 3;
  int last = array[array.length-1];
  array[i] = array[i+1];
  array[0] = last;

  System.out.println(array[i]);
}

I thought that adding 1 to "i" for the array, and storing the last element of the array in "last" and assigning it to array[0] would do the trick, but I'm just getting {3, 3} in the output with "java.lang.ArrayIndexOutOfBoundsException: 3."

Upvotes: 2

Views: 5063

Answers (6)

tdstein
tdstein

Reputation: 1

With O(1) space and O(n) time.

int[] array = new int[3];

for(int i = 0; i < array.length; i++) array[i] = i;

int temp = array[array.length-1];

for(int i = array.length-1; i > 0; i--) array[i] = array[i-1];

array[0] = temp;

Upvotes: 0

Claudio
Claudio

Reputation: 1858

You could try with something like this:

int[] originalArray = ...
int[] shiftedArray = new int[originalArray.length];

System.arraycopy(originalArray, 0, shiftedArray, 1, originalArray.length - 1);
shiftedArray[0] = originalArray[originalArray.length - 1];

EDIT As suggested, only one array is actually needed

int[] originalArray = ...
int lastItem = originalArray[originalArray.length - 1];

System.arraycopy(originalArray, 0, originalArray, 1, originalArray.length - 1);
originalArray [0] = lastItem;

Upvotes: 1

Christoffer
Christoffer

Reputation: 7777

If what you really want is to rotate it (sounds a bit like it). Use Collections.rotate():

Collections.rotate(Arrays.asList(array), 1);

Where 1 is the number of steps (distance)

If you don't want to convert the array to a list you could do the rotate manually with simple methods like this (for example)

Going left:

void rotateArrayLeftByOne(int array[])
{
    // get last index of array
    int lastIndex = array.length - 1; 
    // save first element
    int oldFirst = array[0]; 

    // copy the elements from  right to left
    for (int i = 0; i < lastIndex; i++) 
        array[i] = array[i + 1];

    // put the first element last
    array[lastIndex] = oldFirst;
}

and going right:

void rotateArrayRightByOne(int array[])
{
    // get last index of array
    int lastIndex = array.length - 1; 
    // save last element
    int oldLast = array[lastIndex]; 

    // copy the elements from  left to right
    for (int i = lastIndex; i != 0; i--) 
        array[i] = array[i - 1];

    // put the last element first
    array[0] = oldLast;
}

Upvotes: 7

arunmoezhi
arunmoezhi

Reputation: 3200

you can iterate from end to begin. You begin with creating an empty slot in the end, then start to fill the empty slot with the previous value. There is no need of creating a temporary array. Everything is done in place.

int n=3;
int[] array = new int[n];
int last = array[n-1];    //copy last element into buffer thus creating an empty slot
for(int i=n-1;i>0;i--)    //iterate from end to begin
{
   array[i] = array[i-1]; //push previous element into current location(an empty slot)
}
array[0] = last;          //finally put the last element into initial slot

Upvotes: 0

Camilo Casadiego
Camilo Casadiego

Reputation: 920

First, the problem is that actually your are triying to access a element that doesn't exists. Whe you run this code

array[i] = array[i+1];

and the "i" variable is 2, doing i + 1 will lead you to array[3] which doesn't exists.

Also, working directly with array can lead to memory consumption problems if you are triying to sort, you should better using collections, check http://docs.oracle.com/javase/tutorial/collections/algorithms/ for a good tutorial on how to handle this kind of operations

Upvotes: 0

eazimmerman
eazimmerman

Reputation: 609

You are trying access an index that does not exist in your array. Your array's size is 3 therefore 2 is the last index. Also, you are initializing and printing in the for loop. You should do those outside of the loop.

int[] array = new int[3];

array[0] = 1;
array[1] = 2;
array[2] = 3;

for(int i = 0, previous_value = array[array.length]; i < array.length; i++)
{
  int prev = array[i];
  array[i] = previous_value;
  previous_value = prev;
}

for(int i = 0; i < array.length; i++)
{
System.out.println(array[i]);
}

Upvotes: 0

Related Questions