Skip to content

Commit 8abee66

Browse files
author
Antesh Sharma
committed
Array of int rotation to left and right by d elements
1 parent d1ea839 commit 8abee66

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed
Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
package com.antesh.problems;
2+
3+
import java.util.Arrays;
4+
5+
/* Write a function rotate(ar[], d, n) that rotates arr[] of size n by d elements to right
6+
*
7+
* Sample 1: { 1, 2, 3, 4, 5, 6, 7 }, d = 2, rotate right
8+
* output 1: { 6, 7, 1, 2, 3, 4, 5 }
9+
*
10+
* Sample 1: { 1, 2, 3, 4, 5, 6, 7 }, d = 2, rotate left
11+
* output 1: { 3, 4, 5, 6, 7, 1, 2 }
12+
* */
13+
public class ArrayRotation {
14+
15+
//TC: O(n*d)
16+
public static void rotateRight(int[] arr, int d) {
17+
if (arr == null || arr.length == 0) {
18+
return;
19+
}
20+
int n = arr.length;
21+
int j = 0;
22+
while (j < d) {
23+
int temp = arr[n - 1];
24+
for (int i = 0; i < n; i++) {
25+
int current = arr[i];
26+
arr[i] = temp;
27+
temp = current;
28+
29+
}
30+
j++;
31+
}
32+
}
33+
34+
public static void rotateLeft(int[] arr, int d) {
35+
if (arr == null || arr.length == 0) {
36+
return;
37+
}
38+
int n = arr.length;
39+
rotateRight(arr, n-d);
40+
}
41+
42+
public static void main(String[] args) {
43+
int[] arr = {1, 2, 3, 4, 5, 6, 7};
44+
rotateRight(arr, 1);
45+
System.out.println(Arrays.toString(arr));
46+
47+
int[] arr1 = {1, 2, 3, 4, 5, 6, 7};
48+
rotateRight(arr1, 2);
49+
System.out.println(Arrays.toString(arr1));
50+
51+
int[] arr2 = {1, 2, 3, 4, 5, 6, 7};
52+
rotateLeft(arr2, 2);
53+
System.out.println(Arrays.toString(arr2));
54+
}
55+
}

0 commit comments

Comments
 (0)