1

I am new to recursion and want to know if the below code can be called a recursive function,although the function is calling itself not sure whether it satisfies the condition to have base and recursive cases.

Below function sorts flight tickets based on starting point of the trip ( the trip is assumed to have multiple transitions and tickets are shuffled like ABC-> EFG, XYZ-> MNO, EFG -> KLM , KLM->XYZ).

public List<Ticket> sortTickets(List<Ticket> shuffled, String source, int n) {

    if (sortedList.size() != shuffled.size()) {
        n = (n < 0) ? shuffled.size() - 1 : n;
        if (shuffled.get(n).source == source) {
            sortedList.add(shuffled.get(n));
            source = shuffled.get(n).destination;
            return sortTickets(shuffled, source, n - 1);

        } else {
            return sortTickets(shuffled, source, n - 1);
        }
    } else {
        return sortedList;
    }

}
3
  • Every recursive function should have cases without calling itself, else it would be endless (in theory). => Yes, it´s recursive. Commented May 25, 2014 at 9:09
  • so as long as the function has some finite cases and calls itself can be called recursive ? Not to worry about the base and recursive cases. Commented May 25, 2014 at 9:24
  • As dukeling wrote too, as long it "can" call itself, it´s recursive. Doesn´t matter if it will call itself everytime you use it, or how many finite or infinite case are there. Only infinite cases would be recursive too, but it would make no sense. Commented May 25, 2014 at 9:27

1 Answer 1

2

Every function that calls itself is recursive (regardless of having base cases).

A recursive function without base cases will always infinitely recurse (not that lack of base cases will necessarily prevent infinite recursion - it might be that one of the execution paths of the function never gets to a base case).

Your function has a base case - when sortedList.size() == shuffled.size().

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

1 Comment

Perfect!.I accept this answer.Thanks for pointing to my basecase.

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.