-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathArray_Rotation.java
74 lines (47 loc) · 1.21 KB
/
Array_Rotation.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
/* Take last digit of an array and placed it at front.
* The process run upto n times by user input
*
* Input :
* ----------------
* 5
* 1 2 3 4 5
* 3
*
* Output :
* ----------------
* 3 4 5 1 2
*/
import java.util.Scanner;
public class Array_Rotation {
public static void swap(int[] nums,int i,int j){
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
public static int[] reverse(int[] nums,int i ,int j){
while (i<j) {
swap(nums, i, j);
i++;
j--;
}
return nums;
}
public static void rotate(int[] nums,int k){
k = k%nums.length;
reverse(nums, 0,nums.length-1);
reverse(nums, 0, k-1);
reverse(nums, k, nums.length-1 );
}
public static void main(String[] args) {
int k=3;
int [] nums = {1,2,3,4,5};
for (int i = 0; i < nums.length; i++) {
System.out.print(", "+nums[i]);
}
System.out.println();
rotate(nums, k);
for (int i = 0; i < nums.length; i++) {
System.out.print(", "+nums[i]);
}
}
}