Thursday, June 23, 2011

More Binary search variants

# Search a sorted array of unknown length
# Degree of difficulty: Easy

Assume: Exception will be thrown for array out of bound.

Descriptive answer:
First find the length.
Then do a normal bin search.

How to find the length?
Assume, length 2^n.
Find out valid k for which no exception is thrown.

Again binsearch between 0 and 2^k+1. Consider exception in the
termination criteria.


# Search a sorted array of distinct integer for A[i]=i
# Degree of difficulty: Easy.

def binsearch_var3(list):
l=0
u=len(list)-1
while l<=u:
m=(l+u)/2
print '%d %d' %(m,list[m])
if list[m]==m:
return m
elif list[m] l=m+1
else:
u=m-1

return -1


No comments: