i want to print an array with recurse in java, but the only parameter is the array itself. is it possible?
public static void printintArr(int[] a)
public static void main(String[] args) {
int[] array = new int[] {1, 2, 3, 4, 5};
printArr(array);
}
public static void printArr(int[] a) {
if (a != null && a.length > 0) {
System.out.println(a[0]);
// Call the function printArr with the full array, without the first element
printArr(Arrays.copyOfRange(a, 1, a.length));
}
}
You have to import java.util.Arrays
Output :
1
2
3
4
5
From end:
void printer(int[] input){
if(input.length > 0){
System.out.println(input[input.length-1]);
printer(Arrays.copyOf(input, input.length-1));
}
}
From start:
void printer(int[] input){
if(input.length > 0){
System.out.println(input[0]);
printer(Arrays.copyOfRange(input, 1, input.length));
}
}
The other solutions on here so far all involve copying the entire array minus one element repeatedly. This is exceptionally slow. They run in O(n2) time.
There is a way to do this in O(n) time, but with a List:
public void print(final List<?> list) {
if (list.isEmpty()) {
return;
}
System.out.println(list.get(0));
print(list.subList(1, list.size()));
}
Because subList is a view and not a copy, this method would run in O(n) time as you would expect. Sadly is takes a List and not an array.
Luckily there is a very easy way to get an Object array into a List:
final String[] data = {"a", "b", "c", "d"};
List<String> list = Arrays.asList(data);
This does not copy the array, it simply returns a view of the array as a List. Sadly this does not work for primitive arrays. For that you need to do something like:
final int[] data = {1, 2, 3, 4};
Arrays.stream(data).boxed().collect(toList());
Which does require a copy.
I would point out though that an O(n) copy followed by an O(n) print is still going to be much more efficient than a single O(n2) operation.
O(n^2)?". Although, funnily enough, this is the solution for a cons-list.