Skip to content

Commit 0fdfad3

Browse files
authored
Create Reversal_Algorithm
This is the code for reversal algorithm applied to the 1-D array. Here, we have to rotate the array to the right by k steps. It is the optimised solution for rotating the array.
1 parent 9d1346e commit 0fdfad3

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

Reversal_Algorithm

+31
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
package Algo;
2+
3+
public class Reversal_Algorithm {
4+
5+
public static void main(String[] args) {
6+
// TODO Auto-generated method stub
7+
int []arr= {1,2,3,4,5,6,7};
8+
int k=3;
9+
RotateArray(arr,k);
10+
for(int i=0;i<arr.length;i++) {
11+
System.out.print(arr[i]+" ");
12+
}
13+
}
14+
public static void RotateArray(int []arr,int k) {
15+
int n=arr.length;
16+
k=k%n;
17+
Reverse(arr,0,n-1);
18+
Reverse(arr,0,k-1);
19+
Reverse(arr,k,n-1);
20+
}
21+
public static void Reverse(int []arr,int i,int j) {
22+
while(i<j) {
23+
int temp=arr[i];
24+
arr[i]=arr[j];
25+
arr[j]=temp;
26+
i++;
27+
j--;
28+
}
29+
}
30+
31+
}

0 commit comments

Comments
 (0)