Rotating an array by a given number of positions.
Here’s an example program in Java that rotates an array by a given number of positions:
import java.util.Arrays; public class ArrayRotation { public static void main(String[] args) { int[] arr = {1, 2, 3, 4, 5}; int rotations = 2; System.out.println("Original array: " + Arrays.toString(arr)); rotateArray(arr, rotations); System.out.println("Rotated array: " + Arrays.toString(arr)); } public static void rotateArray(int[] arr, int rotations) { int length = arr.length; // Normalize the number of rotations rotations = rotations % length; // Reverse the entire array reverseArray(arr, 0, length - 1); // Reverse the first part of the array reverseArray(arr, 0, rotations - 1); // Reverse the second part of the array reverseArray(arr, rotations, length - 1); } public static void reverseArray(int[] arr, int start, int end) { while (start < end) { int temp = arr[start]; arr[start] = arr[end]; arr[end] = temp; start++; end--; } } }
In this program, we define an array `arr` and the number of rotations `rotations` that we want to perform. The `rotateArray` method is responsible for rotating the array, while the `reverseArray` method is used to reverse a portion of the array.
The program first prints the original array, performs the rotation, and then prints the rotated array. In this example, the original array is `[1, 2, 3, 4, 5]`, and we rotate it by 2 positions. The expected output will be:
Original array: [1, 2, 3, 4, 5]
Rotated array: [4, 5, 1, 2, 3]
The rotation is done in-place, meaning it modifies the original array rather than creating a new array.
No comments yet! You be the first to comment.