Home > database >  How can I shift the first element of an array to the end of the array?
How can I shift the first element of an array to the end of the array?

Time:09-03

I'm working on a problem that says "Write a method that rotates the elements of an array by one position moving the initial element to the end of the array as shown below." For Example If I have an array { 2, 3, 5, 7, 11, 13 } my output should be { 3, 5, 7, 11, 13, 2 }. Instead I get {13, 2, 3, 5, 7, 11}. While the array is being shifted its being shifted in the wrong direction. I'm not sure what I'm doing wrong here. Can someone explain to my what's wrong with my code? and offer a solution to this?

public static int shift(int[] arr) {
        int temp = 0;
        for (int i = 0; i < 1; i  ) {
            temp = arr[arr.length - 1];
            for (int j = arr.length - 1; j > 0; j--) {
                arr[j] = arr[j - 1];
            }
            arr[0] = temp;
        }
        return temp;
    }
}

CodePudding user response:

I would keep it simple:

public static void shift(int[] arr) {
    int first = arr[0];
    for (int i = 1; i < arr.length; i  ) {
        arr[i - 1] = arr[i];
    }
    arr[arr.length - 1] = first;
}

CodePudding user response:

Use Collections.rotate(). You can rotate a List or an Object array.

A negative argument rotates to the left for the specified number of places. A positive argument rotates right.

Arrays.asList provides a view of the array, so changing the list changes the backing array. Primitive arrays will not work.

Integer[] arr ={2, 3, 5, 7, 11, 13 };
Collections.rotate(Arrays.asList(arr),-1);
System.out.println(Arrays.toString(arr));

prints

[3, 5, 7, 11, 13, 2]
  • Related