Time complexity analysis. choosing operator for counting number of times a line of code runs

前端 未结 1 883
执笔经年
执笔经年 2021-01-25 18:03

Analysing time complexity of this pseudocode. On the right my take on the number of times each line runs. I\'m not sure whether to use log n , n log n , or simply n for the whil

相关标签:
1条回答
  • 2021-01-25 18:52

    If your while loop is:

    3 while i < n                 log n + 1
    4     for j = 1 to n           n log n
    5        sum = sum + j         n log n
    6     i = 2i                   log n
    

    Then yes, you are correct in calculating the complexity. The complexity of the code is indeedO(nlogn).

    Edit:
    Though I am curious what you are trying to do here. You are calculating the sum of 1st n elements logn times.

    Hence the return value would be something like n*(n+1)/2 * logn

    0 讨论(0)
提交回复
热议问题