Python - Linear Search and Binary Search

Peform Linear Search using Python

 
      #linear searching a list of elements
li=[4,5,2,6,7]
a=int(input("Enter a search element"))
found=False
for i in range (0,len(li)):
    if a==li[i]:
        found=True
if found:
    print("Element found in the list")
else:
    print("Element not found in the list")

    
Output

Perform Binary Search using Python

 
      #Binary searching a list of elements
li=[5,6,7,8,1,5]
li.sort()
search_element=int(input("Enter a search element"))
found=False
low=0
high=len(li)-1
while low<=high and found==False:
    midpoint=(low+high)//2
    if li[midpoint]==search_element:
        found=True
    else:
        if search_element>li[midpoint]:
                low=midpoint+1
        else:
            if search_element<li[midpoint]:
                high=midpoint-1
                    
if found:
    print("Element found in the list")
else:
    print("Element not found in the list")

    
Output