Professional Documents
Culture Documents
Binary Search is one of the most important algorithms in the searching scenarios. It is
the most efficient searching algorithm and thus helps us to find a number or a targeted
value given that the array or the list is already sorted.
For example, if we have a dictionary of words sorted numerically, we can easily find a
word by using this binary search. Binary search completes the task in a smaller number
of iterations like if every name of the fruit is written down in a sorted format in an array
and we want to search down a name of a fruit then Binary search will accomplish the task
in a maximum of 11 iterations.
Now we want to search the number 10 from the array. So, our target value is 10.
So to find number 10 in the array we should first divide the array into two parts by finding its middle.
Let us take,
Low = 0
High = 6
(Low and high are the starting and ending index of the given array which is being used to calculate
the middle element)
X [Target Value] = 10
C. But if the Target Value is greater than the Middle Element then it will be present in the right
half of the sorted array. So, we apply the above steps again on the right-hand sided 2nd half
of the array.
D. But if the Target Value is smaller than the Middle Element then it will be present in the left
half of the sorted array. So, we apply the above steps again on the left-hand sided 1st half of
the array.
Here the middle element is 6 which doesn’t match our target value. So, now we check with the 2nd
half of the array because the array is sorted and 10 is greater than 6 so it will lie in the 2nd half.
low: 4
High: 6
Here the middle element is 10 which is itself the target value in the given array.
Now the program will print the index value of the middle array / the target value.
The Binary search is a far more better option than linear search in terms of performance.
Python 3.8.5
lst=[]
n=int(input("Enter No. of Elements: "))
print("Enter Elements:")
for i in range(0,n):
ele=int(input())
lst.append(ele)
print(lst)
print("The Sorted Array is: ")
lst.sort()
print(lst)
x=int(input("Enter The Number To Be Searched: "))
result= bsearch(lst,0,len(lst)-1,x)+1
if result != -1:
print("Element is present at index", str(result-1))
else:
print("Element is not present in array")
Output: