-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReverse_array.java
More file actions
64 lines (54 loc) · 1.9 KB
/
Copy pathReverse_array.java
File metadata and controls
64 lines (54 loc) · 1.9 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
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
package RecursionAndBacktracking;
import java.util.Scanner;
public class Reverse_array {
// By two reference approach
public static int[] reverseArray(int[] a, int left, int right){
if(left >= right){
return a;
}else {
int temp = a[left];
a[left] = a[right];
a[right] = temp;
}
return reverseArray(a, left+1, right-1);
}
// By one reference approach
public static int[] reverseArray_oneReference(int[] a, int index, int size){
if(index >= size/2){
return a;
}
if(index < (size - index - 1)){
int temp = a[index];
a[index] = a[size - index - 1];
a[size - index - 1] = temp;
}
return reverseArray_oneReference(a, index+1, size);
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter number of test cases:");
int t = sc.nextInt();
while (t-- > 0) {
System.out.println("Enter the length of the array : ");
int size = sc.nextInt();
int[] a1 = new int[size];
System.out.println("Enter the elements of the array:");
for (int i = 0; i < size; i++) {
a1[i] = sc.nextInt();
}
int[] a2 = a1.clone();
System.out.println("By two reference approach");
int[] b = reverseArray(a1, 0, size - 1);
for (int ele : b) {
System.out.print(ele + " ");
}
System.out.println();
System.out.println("By one reference approach");
int[] c = reverseArray_oneReference(a2, 0, size);
for(int ele : c){
System.out.print(ele + " ");
}
System.out.println();
}
}
}