forked from python4geeks/Hactoberfest2021
-
Notifications
You must be signed in to change notification settings - Fork 0
/
RotateAnArray.java
129 lines (96 loc) · 2.14 KB
/
RotateAnArray.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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
import java.util.Scanner;
public class RotateAnArray {
public static void rotate(int[] a , int k){
k = k % a.length;
if(k < 0)
{
k = k + a.length;
}
//Part 1
reverse(a, 0 , a.length-k-1);
//Part 2
reverse( a, a.length-k ,a.length-1);
//Part 1 + Part2
reverse(a , 0 , a.length-1);
}
public static void rotate2(int[] a , int k)
{
int[] b = new int[a.length];
int j = 0;
if (k > 0) {
k = k % a.length;
if(k == 0){
return;
}
// if(a.length%k!=0 && k!=1)
// {
// k=k-1;
// }
for (int i = k-1 ; i < a.length; i++) {
b[j] = a[i];
j++;
}
for (int i = 0; i < k-1 ; i++) {
b[j] = a[i];
j++;
}
}
else if(k < 0) {
k = k * -1;
k = k % a.length;
if(k == 0){
return;
}
if(a.length%k!=0)
{
k=k-1;
}
for (int i = k; i < a.length; i++) {
b[j] = a[i];
j++;
}
for (int i = 0; i < k; i++){
b[j] = a[i];
j++;
}
}
else{
return;
}
for(int i = 0;i < a.length;i++){
a[i] = b[i];
}
}
public static void reverse(int[] a,int start , int length){
int low = start;
int high = length;
while(low < high)
{
int temp = a[low];
a[low] = a[high];
a[high] = temp;
low++;
high--;
}
}
private static void Display(int arr[])
{
for (int val : arr) {
System.out.print(val+" ");
}
}
public static void main(String[] args) {
Scanner scn = new Scanner(System.in);
int tc = scn.nextInt();
int arr[] = new int[tc];
for (int i = 0; i < arr.length; i++) {
arr[i] = scn.nextInt();
}
int k = scn.nextInt();
// rotate(arr,k);
// Display(arr);
// System.out.println();
rotate2(arr, k);
Display(arr);
}
}