问题
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 algorithmFor 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:
- Assignment: 3 * n/2 -> O(n)
- Reading access: 2 * n/2 -> O(n)
- 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