Complexity Analysis: how to identify the “basic operation”?

风流意气都作罢 提交于 2021-01-28 05:25:44

问题


I am taking a class on complexity analysis and we try to determin basic operations of algorithms. We defined it as the following:

A basic operation is one that best characterises the efficiency of the particular algorithm of interest

For time analysis it is the operation that we expect to have the most influence on the algorithm’s total running time:
- Key comparisons in a searching algorithm
- Numeric multiplications in a matrix multiplication algorithm
- Visits to nodes (or arcs) in a graph traversal algorithm

For space analysis it is an operation that increases memory usage
- A procedure call that adds a new frame to the run-time stack
- Creation of a new object or data structure in the run-time heap

The basic operation may occur in more than one place in the algorithm

So I'm trying to figure out the basic operation of the ReverseArray Algorithm.

ReverseArray(A[0..n-1])
for i=0 to [n/2]-1 do
   temp <- A[i]
   A[i] <- A[n-1-i]
   A[n-1-i] <- temp

My tutor mentioned a basic operation is a "kind of operation" like assignment, addition, division and that I could either choose between assignment or subtraction in the case of this algorithm.

Now I have an exercise asking about the basic operation of the given algorithm. Is it then correct to say that the basic operation is "assignment" and then list all 3 lines of code inside the for loop?

In my opinion it could be subtraction too, because there are 4 of it.

I'm not really sure if basic operation is a commonly recognized term or if its just an expression my lecturer chose.


回答1:


You can take any operation (assignment, reading array access, subtraction) as basic operation. All would lead to the same result:

  1. Assignment: 3 * n/2 -> O(n)
  2. Reading access: 2 * n/2 -> O(n)
  3. Complete for-block: n/2 -> O(n)

It would made no difference in your example. Here is a stupid example ( no optimized code ), where it makes a difference:

for i = 1 to n do
    x = a[i]
    for j = 1 to n do
        b[j] += x

Obviously, the reading access to array a takes O(n) steps, where the number of writing operations or additions is O(n^2).

The basic operation is the operation on the basis of which you have calculated the complexity. This can be every operation in your code, but this can lead to different results, as I have shown in the example.

For this reason, one often sees phrases like:
The code needs O(n) multiplications and O(n^2) additions.



来源:https://stackoverflow.com/questions/46168440/complexity-analysis-how-to-identify-the-basic-operation

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