Binary Search
Given a sorted array A and an element to search E, find the index of the element using the binary search algorithm. If the element is not found in the array return -1.
Input:
10
2 4 5 6 8 12 15 18 30 54
8
- The first line represents the size of an array.
- The second line represents array elements.
- The third line represents the element to search.
where,
Output:
The given array contains the element 8 at index 4 (index starts from 0).
Code:-
Method 1:-
def solution(arr,x):
l,m,h=0,len(arr)-1,0
while l<=h:
m=(h+l)//2
if arr[m] < x:
l=m+1
elif arr[m] >x :
h=m-1
else:
return m
return -1
arr= []
n=int(input())
# use for loop to fill numbers list with elements
for i in range(n):
s=int(input())
arr.append(s)
print(arr)
x=int(input())
re=solution(arr,x)
if re!=-1:
print(str(re))
else:
print(-1)
Method 2:-
def solution(arr,x):
l=0
h=len(arr)-1
m=int((h+l)//2)
while l<=h:
m=int((h+l)//2)
if arr[m]==x:
return m
if arr[m] < x:
l=m+1
if arr[m] >x :
h=m-1
return -1
arr= []
N=int(input())
L=[]
n=0
for e in input().split():
if(n<N):
arr.append(int (e))
n+=1
x = int(input())
print(solution(arr,x),end='')
0 Comments