1

Hey I am trying to shift elements forward sending the last element in the array to data[0]. I did the opposite direction but I can't seem to find my mistake in going in this direction.

Pos is users inputed shift times amount temp is the temporary holder. data is the array

if(pos > 0)
{
   do
   {
        temp = data[data.length -1];

        for(int i =0; i < data.length; i++)
        {
           if(i == data.length-1)
           {
              data[0] = temp; 
           }
           else
           {
               data[i+1] = data[i];
           }
        }

        pos--;
   } while(pos > 0);
}

Thanks.

Mandar Pandit
  • 2,171
  • 5
  • 36
  • 58

2 Answers2

0

A good idea is to use System.arraycopy.

Please refer to this question Java, Shifting Elements in an Array

Community
  • 1
  • 1
Bruno Volpato
  • 1,382
  • 10
  • 18
0

try this

    int temp = data[data.length - 1];
    for (int i = data.length - 1; i > 0; i--) {
        data[i] = data[i - 1];
    }
    data[0] = temp;

or this

    int temp = data[data.length - 1];
    System.arraycopy(data, 0, data, 1, data.length - 1);
    data[0] = temp;
Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275
  • Your for does not work, and I am not aloud to use array.copy; –  Jun 11 '14 at 23:41
  • Ok so It does work its EXACTLY what I needed, but why is it temp = data.length -1 and not data.length? I had data.length which error before. Can you please explain that for me? Thanks a bunch! –  Jun 12 '14 at 00:43
  • array index starts from 0, if we have int[] a = {1, 2, 3}; then to access last element we use a[2] – Evgeniy Dorofeev Jun 12 '14 at 03:26