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;
}