A Simple Loop

suggest change

The following function finds the maximum element in a nonempty array:

#include <stddef.h>

int find_max(const int array[static 1], size_t length) {
    int max = array[0];
    for (size_t i = 1; i < length; ++i) {
        if (max < array[i]) {
            max = array[i];
        }
    }
    return max;
}

The input size is the size of the array, called length in the code. The caller must provide at least one element; an alternative API could return a status value for empty input.

Let’s count the operations.

int max = array[0];
size_t i = 1;

These two assignments are done only once, so that’s 2 operations. The operations that are looped are:

if (max < array[i])
i++;
max = array[i]

There are three representative operations in the loop, and the loop runs n - 1 times. Adding the two initial assignments gives 3(n - 1) + 2 under this simplified counting model. The exact count is less important than its linear growth, so the function is O(n).

You probably have noticed that “operation” is not very well defined. For instance I said that if (max < array[i]) was one operation, but depending on the architecture this statement can compile to, for instance, three instructions: one memory read, one comparison, and one branch. I have also considered all operations as the same, even though memory operations will be slower than the others, and their performance will vary wildly because of cache effects, for instance. I also have completely ignored the return statement, the fact that a frame will be created for the function, etc. In the end it doesn’t matter to complexity analysis, because whatever way I choose to count operations, it will only change the coefficient of the n factor and the constant, so the result will still be O(n). Complexity shows how the algorithm scales with the size of the input, but it isn’t the only aspect of performance!

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents