-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrotateAnArray.java
More file actions
38 lines (36 loc) · 1.19 KB
/
rotateAnArray.java
File metadata and controls
38 lines (36 loc) · 1.19 KB
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
//Question: Rotate an array to the right by k steps. (Without creating a new array)
// example: arr={1, 2, 3, 4} & k=1 then new arr={4, 1, 2, 3}
package arrays;
import java.util.Scanner;
public class rotateAnArray {
public static void reverse(int[] arr, int i, int j){
while (i<=j) {
int temp=arr[i];
arr[i]=arr[j]; //reverse the elements of the array from ith element to jth element
arr[j]=temp;
i++;
j--;
}
}
public static void main(String[] args) {
// note: k % n = k
System.out.println("Enter the number of elements: ");
Scanner sc= new Scanner(System.in);
int n=sc.nextInt();
int [] arr= new int[n];
System.out.println("Enter the elements of the array: "); // TAKING INPUT(ELEMENTS OF THE ARRAY)FROM USERS
for(int i=0; i<n; i++){
arr[i]= sc.nextInt();
}
System.out.println("Enter the value of k: ");
int k=sc.nextInt();
k=k%n;
reverse(arr, 0, n-k-1);
reverse(arr, n-k, n-1);
reverse(arr, 0, n-1);
System.out.println("New array is: ");
for(int i=0; i<n; i++){
System.out.print(arr[i]+" ");
}
}
}