I have an array:
int[] arr1 = {1, 2, 3, 4, 5, 6, 7, 8, 9};
And I want to rotate the array from a specified range by k
times i.e. from 5th element to last element:
output: {1, 2, 3, 4, 9, 8, 5, 6, 7}
I tried to adapt the algorithm to rotate from start to end of the array
public static int[] rotate(int[] nums, int k) {
int[] a = new int[nums.length];
for (int i = 4; i < nums.length; i++) {
a[(i + k) % nums.length] = nums[i];
}
for (int i = 4; i < nums.length; i++) {
nums[i] = a[i + 4];
}
return nums;
}
However, the output is: 1 2 3 4 0 0 5 6 7
Apart from copying the target elements from the original array into a temporary array and then running this algorithm, what am I doing wrong? Why is 0, 0
returned instead of 9, 8
?