I have two versions of find function, both of which search an integer value in an array and return its position if exists. Function find1()
will search up to N elements in worst case on the other hand find2()
function will search up to N/2 elements in worst case. Does it mean find2()
functions complexity is reduced into O(N/2)?
I assume the array arr
contains non-duplicating values.
Function: find1()
int find1(int value){
for (int i = 0; i < N; i++){
if (arr[i] == value){
return i;
}
}
return -1;
}
Function: find2()
int find2(int value){
for (int i = 0, j = N - 1; i <= j; i++, j--){
if (arr[i] == value){
return i;
}
if (arr[j] == value){
return j;
}
}
return -1;
}
To begin with, the first version does in the worst case n iterations, and, in each iteration, does a constant number of operations. The second version does in the worst case n / 2 iterations, and, in each iteration, also does a constant number of operations, but a larger constant. Thus, there is no reason to think that the first is O(n) and the second is O(n / 2).
In any case, O(n) = O(n / 2). By the definition of O, O(n) means that there is a constant c1 such that for every n > n1,
f(n) < c1 n.
Similarly, O(n / 2) means that there is a constant c2 such that for every n > n2,
f(n) < c2 n / 2 = (c2 / 2) n.
Since for any n > max(n1, n2) the inequality holds for c1 = c2 / 2, each of these two implies the other one.