forked from admirerr/DSA-Collection
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLeftRotation.java
More file actions
33 lines (24 loc) · 870 Bytes
/
LeftRotation.java
File metadata and controls
33 lines (24 loc) · 870 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
import java.util.Arrays;
public class LeftRotation {
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5};
int rotations = 2; // Number of positions to rotate left
System.out.println("Original array: " + Arrays.toString(arr));
leftRotate(arr, rotations);
System.out.println("Array after left rotation: " + Arrays.toString(arr));
}
public static void leftRotate(int[] arr, int rotations) {
int n = arr.length;
rotations = rotations % n;
int[] temp = new int[rotations];
for (int i = 0; i < rotations; i++) {
temp[i] = arr[i];
}
for (int i = rotations; i < n; i++) {
arr[i - rotations] = arr[i];
}
for (int i = 0; i < rotations; i++) {
arr[n - rotations + i] = temp[i];
}
}
}