How can we rotate an array to the left?
Rotating to the left by n is the same as rotating to the right by length-n.
Rotate right (for positive n):
for(int i = 0; i < data.length; i++){ result[(i+n) % data.length ] = data[i];}
Rotate left (for positive n):
for(int i = 0; i < data.length; i++){ result[(i+(data.length-n)) % data.length ] = data[i];}
This way you can avoid a modulo of a negative number.
If you want to input an integer n that rotates right if n is positive and left if n is negative, you can do it like this:
int[] rotateArray(int n, int[] data) { if(n < 0) // rotating left? { n = -n % data.length; // convert to +ve number specifying how // many positions left to rotate & mod n = data.length - n; // rotate left by n = rotate right by length - n } int[] result = new int[data.length]; for(int i = 0; i < data.length; i++){ result[(i+n) % data.length ] = data[i]; } return result; }
In case rotate to the left, you can use this to avoid a modulo of a negative number:
int[] data = {1, 2, 3, 4, 5};int[] result = new int[data.length];for (int i = 0; i < data.length; i++) { result[(i + (data.length - 2)) % data.length] = data[i];}for (int i : result) { System.out.println(i);}
You may also use linkedlist to achieve the same.
Integer[] arr = {1,2,3,4,5}; LinkedList<Integer> ns = new LinkedList<Integer>(Arrays.asList(arr)); int rotate=3; if(rotate<0) rotate += arr.length; List<Integer> leftlist = ns.subList(0, rotate); List<Integer> rightlist = ns.subList(rotate, arr.length); LinkedList<Integer> result = new LinkedList<Integer>(); result.addAll(rightlist); result.addAll(leftlist); System.out.println(result);