Binary Search Function
Programming Interview
Medium
4 views
Problem Description
Consider {x}. Output result.
Input Format
First line n. Second line n integers sorted. Third line x.
Output Format
One integer index.
Official Solution
import sys
lines=sys.stdin.read().splitlines()
if len(lines)<3: sys.exit(0)
n=int(lines[0].strip())
a=list(map(int,lines[1].split()[:n]))
x=int(lines[2].strip())
def bsearch(arr,target):
l=0
r=len(arr)-1
while l<=r:
m=(l+r)//2
if arr[m]==target:
return m
if arr[m]<target:
l=m+1
else:
r=m-1
return -1
sys.stdout.write(str(bsearch(a,x)))
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!