简体   繁体   中英

Time complexity of recursive algorithm

I have a grid with -sided field in it. 字段的网格。 Every field contains a link to it's surrounding fields. 周围字段的链接。 [ ] ]

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)

    The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

     
    粤ICP备18138465号  © 2020-2024 STACKOOM.COM