[FIXED] Java – Rotating array

Issue

So the goal is to rotate the elements in an array right a times.
As an example; if a==2, then array = {0,1,2,3,4} would become array = {3,4,0,1,2}

Here’s what I have:

for (int x = 0; x <= array.length-1; x++){
    array[x+a] = array[x];
}

However, this fails to account for when [x+a] is greater than the length of the array. I read that I should store the ones that are greater in a different Array but seeing as a is variable I’m not sure that’s the best solution.
Thanks in advance.

Solution

Add a modulo array length to your code:

// create a newArray before of the same size as array

// copy
for(int x = 0; x <= array.length-1; x++){
  newArray[(x+a) % array.length ] = array[x];
}

You should also create a new Array to copy to, so you do not overwrite values, that you’ll need later on.

Answered By – Sirko

Answer Checked By – Terry (Easybugfix Volunteer)

Leave a Reply

(*) Required, Your email will not be published