I was asked this question in an interview: Assume an infinite array of integers which is sorted. How would you search for an integer in this array? What would be time complexity? I guessed what the interviewer meant by infinite is that we dont know the value of 'n', where n is the index of the largest number in the array. I gave the following answer:
SEARCHINF(A,i,x){ // Assume we are searching for x
if (A(1) > x){
return
}
if(A(i) == x){
return i;
}
else{
low = i;
high = power(2,i);
if (A(i)>x){
BINARY-SEARCH(A,low,high);
}
else{
SEARCHINF(A,high,x);
}
}// end else
}// end SEARCHINF method
This will find the bound(low and high) in (log x + 1) time in the worst case, when the sorted numbers start from 1 and subsequent numbers are consequent. Then the binary search requires:
O( log {2^(ceil(log x)) - 2^(floor(log x))} )
Is this correct? If correct, can this be optimized?