-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathRotateArrays.java
More file actions
63 lines (57 loc) · 1.57 KB
/
RotateArrays.java
File metadata and controls
63 lines (57 loc) · 1.57 KB
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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
public class RotateArrays {
static void rotateUsingTemp(int arr[], int d, int n)
{
// Storing rotated version of array
int temp[] = new int[n];
// Keeping track of the current index
// of temp[]
int k = 0;
// Storing the n - d elements of
// array arr[] to the front of temp[]
//1, 2, [3, 4, 5, 6, 7]
for (int i = d; i < n; i++) {
temp[k] = arr[i];
k++;
}
// Storing the first d elements of array arr[]
// into temp
// 3, 4, 5, 6, 7, [1, 2]
for (int i = 0; i < d; i++) {
temp[k] = arr[i];
k++;
}
for (int i = 0; i < n; i++) {
System.out.print(temp[i] + " ");
}
}
public static void rotateOneByOne(int arr[], int d, int n)
{
int p = 1;
while (p <= d) {
int last = arr[0];
for (int i = 0; i < n - 1; i++) {
arr[i] = arr[i + 1];
}
arr[n - 1] = last;
p++;
}
// 1, 2, 3, 4, 5, 6, 7
// last = 1
//2, 3, 4, 5, 6, 7, 1
//last = 2
//3, 4, 5, 6, 7, 1, 2
for (int i = 0; i < n; i++) {
System.out.print(arr[i] + " ");
}
}
public static void main(String[] args) {
int arr[] = { 1, 2, 3, 4, 5, 6, 7 };
int N = arr.length;
// Rotate 2 times
int d = 2;
// 3, 4, 5, 6, 7, 1, 2
// Function call
//rotateUsingTemp(arr, d, N);
rotateOneByOne(arr, d, N);
}
}