easyBasic Recursion
Reverse an Array using Recursion
Reverse the order of the values in an array using recursion.
Work through the cases
3 examplesInput notation
One nonempty line of space-separated integers; at most 500 values.Expected result
The reversed values, separated by spaces.Case 1
Input
3 8 2 9
Expected output
9 2 8 3
Case 2
Input
5
Expected output
5
Case 3
Input
-2 0 -2
Expected output
-2 0 -2
These notes use simplified input/output notation. The linked platform defines the method signature and judge format.
FROM IDEA TO IMPLEMENTATION
Understand the approach.
Compare the documented approaches below. Brute force, better, and optimal versions appear where available; a direct exercise may need only one approach.
Swap the endpoints and recurse on the inner range until the pointers meet. Time: O(n); call-stack space: O(n).
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
ArrayList<Long> values = new ArrayList<>();
while (in.hasNextLong()) values.add(in.nextLong());
long[] a = values.stream().mapToLong(Long::longValue).toArray();
long n = a[0];
class R { void f(int l,int r){if(l>=r)return;long v=a[l];a[l]=a[r];a[r]=v;f(l+1,r-1);} } new R().f(0,a.length-1);for(long v:a)System.out.print(v+" ");
}
}
Reference code. Platform solutions may use supplied node types, imports, or collection libraries; foundational examples are complete programs.