Skip to content

Commit 8bfc8f8

Browse files
authored
Merge pull request #212 from AbbeyIT/main
feat: added left rotation in Java
2 parents 06df1e3 + 549e3df commit 8bfc8f8

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

Java/arrays/LeftRotation.java

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
import java.util.Arrays;
2+
3+
public class LeftRotation {
4+
public static void main(String[] args) {
5+
int[] arr = {1, 2, 3, 4, 5};
6+
int rotations = 2; // Number of positions to rotate left
7+
8+
System.out.println("Original array: " + Arrays.toString(arr));
9+
10+
leftRotate(arr, rotations);
11+
12+
System.out.println("Array after left rotation: " + Arrays.toString(arr));
13+
}
14+
15+
public static void leftRotate(int[] arr, int rotations) {
16+
int n = arr.length;
17+
18+
rotations = rotations % n;
19+
20+
int[] temp = new int[rotations];
21+
for (int i = 0; i < rotations; i++) {
22+
temp[i] = arr[i];
23+
}
24+
25+
for (int i = rotations; i < n; i++) {
26+
arr[i - rotations] = arr[i];
27+
}
28+
29+
for (int i = 0; i < rotations; i++) {
30+
arr[n - rotations + i] = temp[i];
31+
}
32+
}
33+
}

0 commit comments

Comments
 (0)