-
Notifications
You must be signed in to change notification settings - Fork 3
/
rotate_an_array.java
56 lines (44 loc) · 974 Bytes
/
rotate_an_array.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
import java.util.*;
import java.io.*;
public class reverse_of_an_array{
public static void display(int[] a){
StringBuilder sb = new StringBuilder();
for(int val: a ){
sb.append(val + " ");
}
System.out.println(sb);
}
public static void reverse(int[] a,int i, int j){
int li = i;
int ri = j;
while(li < ri){
int temp = a[li];
a[li] = a[ri];
a[ri] = temp;
li++;
ri--;
}
}
public static void rotate(int[] a, int k){
k = k % a.length;
if(k < 0){
k += a.length;
}
//part1
reverse(a, 0, a.length - k -1);
//part2
reverse(a, a.length - k, a.length - 1);
//all
reverse(a, 0, a.length - 1);
}
public static void main(String args[]) throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
int[] a = new int[n];
for(int i = 0; i < a.length;i++){
a[i] = Integer.parseInt(br.readLine());
}
rotate(a,k);
display(a);
}
}