1
def busca(num, a, primeiro, ultimo):
meio = int((primeiro + ultimo) / 2)
if num == a[meio]:
return meio
elif num < a[meio]:
return busca(num, a, primeiro, meio)
else:
return busca(num, a, meio+1, ultimo)
arr = [int(x) for x in raw_input().split()]
tamArray = arr[0]
numQuery = arr[1]
arr = []
arr = [int(x) for x in raw_input().split()]
i = 0
while i < numQuery:
num = int(input())
try:
print(busca(num, arr, 0, tamArray-1))
except:
print(-1)
i += 1
This is the code. The Moji question asks for the following entries: First entry: N and Q, where N is the number in the ordered array and Q is the number of searches to be performed.
Second entry: Ordered array
Next Q entries: numbers to be searched.
For each search, you must return the position of the number in the vector (starting with 0) and, if not found, return -1
This is the link to the exercise in case anyone has doubts yet: http://www.spoj.com/problems/BSEARCH1/
Python 3+ or Python 2.7-? I say this because of
input
vsraw_input
. Does it make any suggestions as to how it has to be resolved ? Binary search can be solved without recursion, which can imply that the same algorithm is tested for a larger input of values and fails for excessive time, for example– Isac