How to define what is the elementary operation in an algorithm?

1.3k Views Asked by At

I always thought that the elementary operation from an algorithm was the operation located inside the most inner loop. I found very little detail about this in books and online articles, maybe because it was supposed to be something trivial, but the few that cared to explain what should be the elementary operation in an algorithm, they always says that its the operation that is executed the most, that is, the one located inside the most inner loop.

And as such, in this algorithm:

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);

        while (true) {
            int N = in.nextInt();
            if (N == 0)
                break;

            long cost = 0;
            int[] houses = new int[N];
            for (int i = 0; i < N; ++i)
                houses[i] = in.nextInt();

            for (int i = 0; i < N - 1; ++i) {
                cost += Math.abs(houses[i]);
                houses[i + 1] += houses[i];
            }
            System.out.println(cost);
        }
    }
}

I said that the elementary operation was the assignment operation houses[i] = in.nextInt(); inside the first for, because it runs N times while the second for runs N-1 times.

My teacher is saying that this is incorrect and that the elementary operation in this algorithm is the operation inside the second for.

By any chances, there has exceptions where the elementary operation isn't the operation located inside the most inner loop, or she is wrong?

2

There are 2 best solutions below

2
On

For this program, the second for loop is not inside the first for loop.

This program takes N numbers as inputs for the houses array and the actual algorithm is only in the second for loop, where it keeps the running count of the cost of the first i items of the array in the ith index.

Your teacher is correct.

0
On

An elementary operation is one whose execution time is bounded by a constant for a particular machine and programming language. That means if we run an elementary operation written in a specific language on a specific machine, it always takes the same time to be executed. Such as assignment, addition, multiplication, etc. In your case, the operation in.nextInt(); under the first loop actually is a keyboard input event, kind of IO operations, which depends mainly on users. So it's not an elementary operation.