Searching
Searching
l=[]
n=int(input("Enter no of elements in the list "))
for i in range(0,n):
print("Enter the value")
l.append(int(input()))
key = int(input("Enter the element to search "))
found=0
for i in range(0,n):
if l[i]==key:
found=found+1
if found>0:
print("Element Found in the list ")
else:
print("Element Not Found in the list ")
OUTPUT:
Enter no of elements in the list 5
Enter the value
89
Enter the value
88
Enter the value
38
Enter the value
108
Enter the value
68
Enter the element to search 38
Element Found in the list
# BINARY SEARCH
def binary_search():
n=int (input("enter the number of elements : "))
data =[]
for i in range(n):
print("Enter the value")
v=int(input())
data.append(v)
data.sort()
key=int(input("enter the element to be found :"))
low=0;high=len(data)-1;mid=0
while low<=high:
mid=(low+high)//2
if data[int(mid)]==key:
print("element found at index :",mid)
break
elif data[int(mid)]<key:
low=mid+1
else:
high=mid-1
else:
print("element not found")
binary_search()
OUTPUT: