-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReverseArrayRecursivelyIteratively.java
More file actions
59 lines (52 loc) · 1.24 KB
/
ReverseArrayRecursivelyIteratively.java
File metadata and controls
59 lines (52 loc) · 1.24 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
public class ReverseArrayRecursivelyIteratively
{
public static void initArray(int [] array)
{
for (int i = 0; i < array.length; ++i)
{
array[i] = i+1;
}
}
public static int[] ReverseArrayIteratively(int[] array)
{
for (int i = 0; i < array.length/2; ++i)
{
int temp = array[i];
array[i] = array[array.length-i-1];
array[array.length-i-1] = temp;
}
return array;
}
public static void printArray(int[] array)
{
for (int i : array)
{
System.out.printf("%d ",i);
}
System.out.println("\n");
}
public static int[] ReverseArrayRecursively(int[] array, int size, int index)
{
if ( size != array.length/2 )
{
int temp = array[index];
array[index] = array[array.length-size-1];
array[array.length-size-1] = temp;
return ReverseArrayRecursively(array,size+1,index+1);
}
return array;
}
public static void main(String[] args)
{
int [] array = new int[15];
initArray(array);
System.out.println("Array initialized: ");
printArray(array);
array = ReverseArrayIteratively(array);
System.out.println("Iteratively reverse array called: ");
printArray(array);
array = ReverseArrayRecursively(array,0,0);
System.out.println("Recursively reverse array called: ");
printArray(array);
}
}