-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReverseArr.java
More file actions
47 lines (42 loc) · 1.15 KB
/
Copy pathReverseArr.java
File metadata and controls
47 lines (42 loc) · 1.15 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
//Reverse array or a string
public class ReverseArr {
public static void main(String[] args) {
int[] arr = { 1, 2, 3, 4, 5 };
String s = "abcdef";
System.out.println(revStr(s));
printArray(arr);
rArray(arr);
printArray(arr);
}
// print an array
static void printArray(int[] arr) {
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
}
// reverse array
static void rArray(int[] arr) {
// reverse array through swapping the elements
int l = 0;
int r = arr.length - 1;
int temp;
while (l <= r) {
temp = arr[l];
arr[l] = arr[r];
arr[r] = temp;
l++;
r--;
}
}
// reverse string or we can use toCharArray() method to convert the string into
// an character array and then reverse it by swapping the elements.
static String revStr(String s) {
String revS = "";
char ch;
for (int i = s.length() - 1; i >= 0; i--) {
ch = s.charAt(i);
revS += ch;
}
return revS;
}
}