I was looking through some old notes on algorithms today, and it made me think.
Complexity O(1)means that the execution time of a function is data independent.
So, suppose we have a function to add all elements to an array.
int add(int[] array){
int sum =0;
for (int i=0;i<ARRAY_MAX_SIZE;i++){
sum= sum + (i<array.length?array[i]:0);
}
return sum;
}
where ARRAY_MAX_SIZEis the maximum possible size of the array. I know that this code is inefficient, I do not want to discuss this. But +each time an operator is called the same amount of time, and it is not affected by the size of the data.
Does this mean that the complexity of this function is O (1)?
source
share