开发者

Time complexity of recursive algorithm

I have a grid with x-sided field in it. Every field contains a link to it's x surrounding fields. [x is constant]

I have an algorithm which is implemented in this field, (which can probably be optimized):

[java like pseudocode]

public ArrayList getAllFields(ArrayList list) {

  list.addToList(this);

  for each side {
    if ( ! list.contains(neighbour) && constantTimeConditionsAreMet()) {
      neighbour.getAllFields(list) //Recursive call
    }
  }

  return list;

}

I'm having trouble finding the time complexity.

  • ArrayList#contains(Object) runs in linear time
  • How do i find the time complexity? My approach is this:

    T(n) = O(1) + T(n-1) +
    c(nbOfFieldsInArray - n) [The time to check the ever filling ArrayList]
    
    T(n) = O(1) + T(n-1) + c*nbOfFieldsInArray - cn
    

    Does this give me T(n) = T(开发者_运维问答n-1) + O(n)?


    The comment you added to your code is not helpful. What does getContinent do?

    In any case, since you're using a linear search (ArrayList.contains) for every potential addition to the list, then it looks like the complexity will be Omega(n^2).


    You recurrence seems correct T(n) = T(n-1) + theta(1).

    If you draw the recursion tree you'll notice you have a single branch with the values theta(n-1), theta(n-2), ..., theta(2), theta(1), if you add up all the levels you get the arithmetic series 1+2+3+...+n

    S1 = 1+2+3+...+n
    

    If you define

    S2 = n+...+3+2+1
    

    and then calculate S1+S2 you get

    S1 + S2 = 2*S1 = (n+1) + (n+1) + ... + (n+1) = n(n+1)
    

    therefore

    2*S1 = n(n-1) => S1 = n(n-1)/2
    

    which means T(n) = 1/2 theta(n(n-1)) = 1/2 theta(n^2) = theta(n^2)

    0

    上一篇:

    下一篇:

    精彩评论

    暂无评论...
    验证码 换一张
    取 消

    最新问答

    问答排行榜