- Notifications
You must be signed in to change notification settings - Fork 366
/
Copy pathLeftRotateArrayByD.java
60 lines (52 loc) · 1.44 KB
/
LeftRotateArrayByD.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
packagecom.company;
publicclassLeftRotateArrayByD {
//Reversal Algorithm-->
staticvoidreverse(int[] arr, intlow, inthigh){
inttemp=0;
while (low<high) {
temp = arr[low];
arr[low] = arr[high];
arr[high] = temp;
low++;
high--;
}
}
staticvoidleftRotate(int[] arr, intd){
if (d==0)
return;
intn=arr.length;
reverse(arr,0,d-1);
reverse(arr, d,n-1);
reverse(arr,0,n-1);
}
// Better Method-->
// static void leftRotate(int[] arr, int d){
// int[] temp = new int[d];
// for (int i=0; i<d; i++)
// temp[i]=arr[i];
// for (int i=d; i< arr.length; i++)
// arr[i-d]=arr[i];
// for (int i=0; i<d; i++)
// arr[arr.length-d+1]=temp[i];
// }
// Naive Method-->
// static void leftRotateOne(int[] arr){
// int n = arr.length;
// int temp = arr[0];
// for (int i=1; i<arr.length; i++)
// arr[i-1]=arr[i];
// arr[n-1]=temp;
// }
// static void LeftRotate(int[] arr, int d){
// for (int i=0; i<d; i++)
// leftRotateOne(arr);
// }
publicstaticvoidmain(String[] args) {
int[] arr = newint[]{1,2,3,4,5};
intd = 2;
intn = arr.length;
leftRotate(arr, 2);
for (inti=0; i<n; i++)
System.out.print(arr[i] + " ");
}
}