import java.util.Arrays;
public class LeftRotateArray {
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5};
int n = arr.length;
int d = 2;
System.out.println("Original array: " + Arrays.toString(arr));
// left rotate array by d positions
for (int i = 0; i < d; i++) {
int temp = arr[0];
for (int j = 1; j < n; j++) {
arr[j - 1] = arr[j];
}
arr[n - 1] = temp;
}
System.out.println("Array after left rotation: " + Arrays.toString(arr));
}
}
Original array: [1, 2, 3, 4, 5]
Array after left rotation: [3, 4, 5, 1, 2]
arr
and initialize it with the values {1, 2, 3, 4, 5}
. We get the length of the array n
and declare an integer variable d
to specify the number of positions to rotate the array.for
loop to left rotate the array by d
positions. In the outer loop, we repeat the left rotation process d
times. In the inner loop, we shift each element of the array one position to the left, except for the first element, which we store in a temporary variable temp
. After the inner loop completes, we assign the value of temp
to the last element of the array.System.out.println()
and Arrays.toString()
.