To write a program to perform linear search and binary search using python programming.
- Hardware – PCs
- Anaconda – Python 3.7 Installation / Moodle-Code Runner
- Start from the leftmost element of array[] and compare k with each element of array[] one by one.
- If k matches with an element in array[] , return the index.
- If k doesn’t match with any of elements in array[], return -1 or element not found.
- Set two pointers low and high at the lowest and the highest positions respectively.
- Find the middle element mid of the array ie. arr[(low + high)/2]
- If x == mid, then return mid.Else, compare the element to be searched with m.
- If x > mid, compare x with the middle element of the elements on the right side of mid. This is done by setting low to low = mid + 1.
- Else, compare x with the middle element of the elements on the left side of mid. This is done by setting high to high = mid - 1.
- Repeat steps 2 to 5 until low meets high
#Developed by:KAVINAJAI.T
#Register number:212223100020
def linearSearch(array,n,k):
for i in range(0,n):
if(array[i]==k):
return i
return -1
array=eval(input())
k=eval(input())
n=len(array)
array.sort()
result=linearSearch(array,n,k)
if(result==-1):
print(array)
print("Element not found")
else:
print(array)
print("Element found at index: ",result)
Developed by:KAVINAJAI.T
#Register number:212223100020
def binary(array,key,low,high):
while(low<=high):
mid=low+(high-low)//2
if array[mid]==key:
return mid
elif array[mid]<key:
low=mid+1
elif array[mid]>key:
high=mid-1
return -1
array=eval(input())
key=int(input())
array.sort()
low,high=0,len(array)-1
print(array)
result=binary(array,key,low,high)
if result==-1:
print("Element not found ")
else:
print("Element found at index: ",result)
#Developed by: KAVINAJAI.T
#Register number:212223100020
def binary(array,key,low,high):
if high>=low:
mid=low+(high-low)//2
if array[mid]==key:
return mid
elif array[mid]<key:
return binary(array,key,mid+1,high)
elif array[mid]>key:
return binary(array,key,low,mid-1)
return -1
array=eval(input())
key=int(input())
array.sort()
low,high=0,len(array)-1
print(array)
result=binary(array,key,low,high)
if result==-1:
print("Element not found")
else:
print("Element found at index: ",result)
Thus the linear search and binary search algorithm is implemented using python programming.