Binary search is an efficient algorithm for finding an item from a sorted list of items. It works by repeatedly dividing in half the portion of the list that could contain the item, until you've narrowed down the possible locations to just one.
Linear Search | Binary Search |
---|---|
Linear search is an algorithm to find an element in a list by sequentially checking the elements of the list until finding the matching element | Binary search is an algorithm that finds the position of a target value within a sorted array. |
A linear search scans one item at a time without skipping to any item. | A binary search cuts down the search to half as soon as the middle of a sorted list is found. |
Linear search is easy to use because there is no need for any ordered elements. | The binary search is a bit complicated with elements being necessarily arranged in a given order. |
def bsearch(L,n):
start=0
end=len(L)-1
while start<=end:
mid=(start+end)//2
if L[mid]==n:
return True
elif L[mid]<=n:
start=mid+1
else:
end=mid-1
else:
return
False
L=eval(input("Enter the list of numbers"))
n=int(input("Enter the list of numbers"))
L.sort()
if bsearch(L,n):
print("Letter found")
else:
print("Letter not found")
- Binary search is an efficient algorithm for finding an item from a sorted list of items.
- It works by repeatedly dividing in half the portion of the list that could contain the item.
- Eases the tasks in Python
- Used In #C programming language
- better than linear search in every aspect