- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReverse_array.java
More file actions
Latest commit
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
packageRecursionAndBacktracking;
importjava.util.Scanner;
publicclassReverse_array {
// By two reference approach
publicstaticint[] reverseArray(int[] a, intleft, intright){
if(left >= right){
returna;
}else {
inttemp = a[left];
a[left] = a[right];
a[right] = temp;
}
returnreverseArray(a, left+1, right-1);
}
// By one reference approach
publicstaticint[] reverseArray_oneReference(int[] a, intindex, intsize){
if(index >= size/2){
returna;
}
if(index < (size - index - 1)){
inttemp = a[index];
a[index] = a[size - index - 1];
a[size - index - 1] = temp;
}
returnreverseArray_oneReference(a, index+1, size);
}
publicstaticvoidmain(String[] args) {
Scannersc = newScanner(System.in);
System.out.println("Enter number of test cases:");
intt = sc.nextInt();
while (t-- > 0) {
System.out.println("Enter the length of the array : ");
intsize = sc.nextInt();
int[] a1 = newint[size];
System.out.println("Enter the elements of the array:");
for (inti = 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 (intele : b) {
System.out.print(ele + " ");
}
System.out.println();
System.out.println("By one reference approach");
int[] c = reverseArray_oneReference(a2, 0, size);
for(intele : c){
System.out.print(ele + " ");
}
System.out.println();
}
}
}