-
Notifications
You must be signed in to change notification settings - Fork 67
/
Copy pathArrayRotation.java
74 lines (67 loc) · 1.52 KB
/
ArrayRotation.java
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
64
65
66
67
68
69
70
71
72
73
74
package com.java.array;
import java.util.Arrays;
/*
* Rotate the Given array d times
* -------------------------------
* Write java program to rotate (clockwise) the given array
* d number of times.
*
* Steps:
* 1. Create new array of same size
* 2. Create a new index variable new_index = 0
* 3. Copy the array from index d to n
* to the new array of index 0, and increment new_index
* 4. Copy the array from index 0 to d
* to the new array and increment new_index.
*
* Given array is {1, 2, 3, 4, 5, 6}
* d = 2
*
* New array = {0, 0, 0, 0, 0, 0}
*
* copy index from d to n to new array
* New array = {5, 6, 0, 0, 0, 0}
*
* copy index from 0 to d to new array
* New array = {5, 6, 1, 2, 3, 4}
*
* Finally after rotation
* {5, 6, 1, 2, 3, 4}
*
*/
public class ArrayRotation {
public static void main(String[] args) {
int arr[] = {1, 2, 3, 4, 5, 6};
int d = 6;
int n = arr.length;
if(d > n)
d = d-n;
int new_arr[] = new int[n];
int new_index = 0;
for(int i=(n-d);i<n;i++,new_index++)
new_arr[new_index] = arr[i];
for(int i=0;i<(n-d);i++,new_index++)
new_arr[new_index] = arr[i];
System.out.println("Original Array ");
System.out.println(Arrays.toString(arr));
System.out.println("Array after rotation");
System.out.println(Arrays.toString(new_arr));
}
}
/*
INPUT
arr[] = {1, 2, 3, 4, 5, 6}
d = 2
OUTPUT
{5, 6, 1, 2, 3, 4}
INPUT
arr[] = {1, 2, 3, 4, 5, 6}
d = 4
OUTPUT
{3, 4, 5, 6, 1, 2}
INPUT
arr[] = {1, 2, 3, 4, 5, 6}
d = 6
OUTPUT
{1, 2, 3, 4, 5, 6}
*/