Hi Guys,
In this post, we will see the simplest java program to rotate array elements.
Java program to Right Rotate array elements by N:
package basics; import java.util.Arrays; public class MainApp { public static void main(String[] args) { int[] a1 = { 1, 2, 3, 4, 5, 6, 7 }; int[] a2 = new int[a1.length]; int rotate = 3; //to rotate right rotate = a1.length-rotate; for (int i = 0; i < a1.length; i++) { a2[i] = a1[rotate]; rotate++; if (rotate == a1.length) { rotate = a1.length - rotate; } } System.out.println("Before rotate :"+Arrays.toString(a1)); System.out.println("After rotate :"+Arrays.toString(a2)); } }
Output:
Before rotate :[1, 2, 3, 4, 5, 6, 7] After rotate :[5, 6, 7, 1, 2, 3, 4]
Java program to Left Rotate array elements by N:
package basics; import java.util.Arrays; public class MainApp { public static void main(String[] args) { int[] a1 = { 1, 2, 3, 4, 5, 6, 7 }; int[] a2 = new int[a1.length]; int rotate = 3; for (int i = 0; i < a1.length; i++) { a2[i] = a1[rotate]; rotate++; if (rotate == a1.length) { rotate = a1.length - rotate; } } System.out.println("Before rotate :"+Arrays.toString(a1)); System.out.println("After rotate :"+Arrays.toString(a2)); } }
Before rotate :[1, 2, 3, 4, 5, 6, 7] After rotate :[4, 5, 6, 7, 1, 2, 3]