Todays Lecture Code

def linear_search(arr,x):
n=len(arr)
for i in range(0,n):
if (arr[i]==x):
return i
return -1

def binary_search(arr,x):
n=len(arr)
# first idx
low=0
# last idx
high=n-1

while(low<=high):  
    mid=(low+high)//2 
    if(arr[mid]==x):
        return mid 
    elif (arr[mid]<x):   #arr[mid]->2  x->5  if 2<5
        low=mid+1 
    else:
        high=mid-1 
else:
    return -1

sorted list

arr=[1,2,3,4,5]

time complexity->O(log n)

ans=linear_search(arr,8)
print(ans)

1 Like