78.7k views
4 votes
1. Create a recursive method that reverses an ArrayList.

2. Create a recursive method to determine whether a number is prime.
3. Write recursive code to split an ArrayList A into two ArrayLists B and C such that B contains all even numbers of A and B contains all odd numbers of A.

User MewX
by
7.2k points

1 Answer

2 votes

Final answer:

To reverse an Array List recursively, create a method that swaps the first and last elements of the list. To determine whether a number is prime recursively, create a method that checks if it is divisible by any number from 2 to its square root. To split an Array List into two based on even and odd numbers, create a method that checks each element and adds it to the corresponding list.

Step-by-step explanation:

1. To reverse an Array List recursively, you can create a recursive method that swaps the first and last elements of the list, then recursively calls itself on the sub list.

public void reverse List (Array List<T> list) {
if (list. Size () <= 1) {
return; // Base case
}
T first Element = list. Remove (0).
reverse List(list).
list. Add(firstElement);
}

2. To determine whether a number is prime recursively, you can create a method that checks if the number is divisible by any number from 2 to its square root. If it is not divisible by any of those numbers, it is prime.

public Boolean is Prime (int num, int divisor) {
if (num <= 2) {
return num == 2.
}
if (divisor > Math.sqrt(num)) {
return true; // Base case, num is prime.
}
if (num % divisor == 0) {
return false; // Base case, num is not prime.
}
return is Prime (num, divisor + 1); // Recursive case.
}

3. To split an Array List A into two Array Lists B and C based on whether the elements are even or odd, you can create a recursive method that checks each element and adds it to either list B or list C.

public void split List (Array List<Integer> list, Array List<Integer> even List, Array List<Integer> odd List) {
if (list.isEmpty()) {
return; // Base case
}
int element = list. Remove (0).
if (element % 2 == 0) {
evenList.add(element).
} else {
oddList.add(element).
}
split List (list, even List, odd List).
}
User Ayrton Senna
by
7.6k points