I was asked this question in an interview: suppose an infinite array of integers is sorted. How would you look for an integer in this array? What will be the time complexity? I guessed that the interviewer meant infinite, so that we do not 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
In the worst case, the associated (low and high) value (log x + 1) will be found when the sorted numbers start at 1 and subsequent numbers. Then for binary search you need:
O( log {2^(ceil(log x)) - 2^(floor(log x))} )
It is right? If this is correct, can this be optimized?
Brahadeesh
source share