1

My homework is to create a recursive static method that receives an arraylist of integers as a parameter. Say that there are elements which have a value of 0 and I want to switch it to 5, elements which have a value of 1 are removed, and elements which have a value of 2 are moved to the end. The rest stays as is.

I can think of ways to do it without using recursion, but how could I solve this problem with using recursion?

Thank you.

0

2 Answers 2

3

This doesn't at all feel like a problem that lends itself to recursion to me. That said if you are desperate to do it that way, look into using List.subList as a way to artificially construct a "recursive" case (by chopping off elements from the front) and use a "base" case of an empty list.

Sign up to request clarification or add additional context in comments.

3 Comments

And don't forget to apply sort in the end. You can do it before starting all that, but doing it in the end save you a little time because there would be less elements, most likely.
"The homework is to create a recursive static method". Looks to me like recursion is a requirement here.
@Andreas_D: Doesn't mean you can't complain about it!
2

Your base case is a list of length 1, which is easy to deal with.

A list of length 2, where you know the last 1 element has already been processed, is only slightly harder to deal with.

A list of length N, where you know the last N-1 elements have been processed, should be manageable.

So, what you can do is take the list, pass the list minus the first element down to the next level of recursion, then when you get the processed sub-list back, deal with that one first element.

@Steven Schlansker is right, though, this is not really a recursion-friendly task.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.