Binary and Linear search(PYTHON)
def binary_search(size, list1, z):
list1.sort()
low = 0
high = size-1
index = -1
while(low <= high):
mid = (low+high)//2
if list1[mid] < z:
low = mid+1
elif list1[mid] > z:
high = mid-1
elif list1[mid] == z:
index = mid
print("found at index: ", mid)
break
if index == -1:
print("Not found")
def linear_search(size, list1, z):
index = -1
for i in range(size):
if list1[i] == z:
index = i
print("found at index :", i)
break
if index == -1:
print("Not found")
print("enter the size of list : ")
n = int(input())
l = [int(input("enter the elements")) for i in range(n)]
print("enter the element to be searched :")
z = int(input())
binary_search(n, l, z)
linear_search(n, l, z)
Comments
Post a Comment