Alex Rivera | Logout

Run-time complexities for recursive algorithms

Asked 2012-03-02T21:34:52.023
8

I've searched high and low and can't seem to find a lot of material related to run-time complexities, recursion, and java.

I'm currently learning run-time complexities and Big-O notation in my Algorithms class, and I'm having trouble analyzing recursive algorithms.

private String toStringRec(DNode d)
{
   if (d == trailer)
      return "";
   else
      return d.getElement() + toStringRec(d.getNext());
}

This is a recursive method that will simply iterate though a doubly-linked list and print out the elements.

The only thing I can come up with is that it has a run-time complexity of O(n), since the number of recursive method calls will depend on the number of nodes in the DList, but I still don't feel comfortable with this answer.

I'm not sure whether I should be accounting for the addition of d and d.getNext().

Or am I just completely off track and the run-time complexity is constant, since all its doing is retrieving elements from the DNodes in the DList?

Edit
Report

2 Answers

2

This is a pretty simple example, but the trick is to define a recurrence relation, which is a function of the runtime of a given input size in terms of smaller input sizes. For this example, assuming that the work done at each step takes constant time C and assuming that the base case does no work, it would be:

T(0) = 0
T(n) = C + T(n-1)

You can then solve for running time using substitution to find a series:

T(n) = C + T(n-1) = 2C + T(n-2) = 3C + T(n-3) = ... = nC + T(n-n) = nC + 0 = nC

By the definition of O, this equation is O(n). This example isn't particularly interesting, but if you look at something like the runtime of mergesort or another divide and conquer algorithm you can get a better idea of recurrence relations.

answered 2012-03-02T21:57:05.110
0

The algorithm has run-time complexity of O(n) as you suggest. Your list has n items in it, and the algorithm will do a near-fixed amount of work for each item (that work being Element and Next access, plus a new toStringRec call). Retrieving an Element from a DNode takes constant time, and constant times are discarded in big-O notation.

The interesting thing about recursive methods (in most cases) is that they are also O(n) in space complexity too. A new stack entry (to store the parameters passed to the method) is created for each call to toStringRec, which is called n times.

answered 2012-03-02T21:48:41.987

Your Answer