Issue
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;
}
}
Solution
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;
}
Answered By - Bohemian
Answer Checked By - Willingham (JavaFixing Volunteer)