top of page
  • Subham Das

Binary Search

If a list of elements or records are in sorted in ascending order the Binary Search algorithm is applicable. Its is faster than Insertion search. In this case three index value is considered with assigning the first or the lower value as 0 and high or the last value as length of that list. And the adding the index of lower and higher divided by 2 (float division), we get mid index.


Binary search compares the target value to the middle element of the array. If they are not equal, the half in which the target cannot lie is eliminated and the search continues on the remaining half, again taking the middle element to compare to the target value, and repeating this until the target value is found. If the search ends with the remaining half being empty, the target is not in the array.



# Program for Binary Search.

# You can take list from user or assign a list but remember the list should be sorted.


list = [2,5,8,12,16,23,38,56,72,91]

# Hereke input from user of the searching element.


searchfor = eval(input("Enter the element for search:"))

flag = 0

low = 0

high = len(list)-1

while low<= high :

mid = (low+high)//2

if searchfor == list[mid] :

flag = 1

# Here position variable will help us to tell the the position of the element in the list.

position = mid+1

# Here break statement help to jump out of loop it the condition satisfies.

break

else :

if searchfor > list[mid] :

low = mid+1

else:

high = mid-1

if flag == 1 :

print(searchfor,"is in the List in postion:",position)

else :

print(searchfor,"is not in the List")












37 views0 comments

Recent Posts

See All
logo12.PNG
bottom of page