overall time complexity of the program?

帅比萌擦擦* 提交于 2020-04-16 02:05:44

问题


suppose you take 'n' inputs in an array(and for that you have to run a loop that iterates 'n' times for 'n' different locations), which would have O(n) complexity.

And then you you try to perform operations that have O(log n) or less than O(n) time complexity. my question here is that does it really matter to have complexity of those operations less than O(n) since your whole program will have atleast O(n) time complexity. 


回答1:


Indeed, a program's time complexity could be dominated by the time it takes to read the input. For example, if a program reads an array from input, then does one binary search in that array, the time complexity is Θ(n) simply because of reading the input.

A program's time complexity could also be dominated by the time it takes to generate the output. For example, a tree with n vertices has n-1 edges, so many algorithms on trees can run in Θ(n) time; but if we want to print the adjacency matrix then there's no way to do that in better than Θ(n2) time because the output is a 2D array with n2 elements.

I think there's an implicit follow-up question: so how can an algorithm ever run in less than Θ(n) time? Note that the above is talking about programs which do IO. The binary search algorithm takes Θ(log n) time, because reading the input is not done by the binary search algorithm itself. An algorithm is only part of a program; the array is read from input by a different part of the program, so it exists in memory before the algorithm is run, and the algorithm gets access to it via a reference. That means the algorithm receives its input, of size n, in Θ(1) time.




回答2:


No, it doesn't matter in big-O terms, as in your example the input loop O(n) dominates over further O(log n) operations. See infinite asymptotics:

Big O notation is useful when analyzing algorithms for efficiency. For example, the time (or the number of steps) it takes to complete a problem of size n might be found to be T(n) = 4n2 − 2n + 2. As n grows large, the n2 term will come to dominate, so that all other terms can be neglected



来源:https://stackoverflow.com/questions/60063034/overall-time-complexity-of-the-program

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!