Binary Search
Algorithm: Binary
Search
Input: A list
of sorted elements and the element to be searched.
Output: Position
of the element if found, otherwise a message saying that the element is not
found.
Steps:
§
Start the process.
§
Read the list of elements.
§
Sort the list in ascending order.
§
Read the element that needs to be searched.
§
Set bottom to the first index of the list.
§
Set top to the last index of the list.
§
Repeat the following steps until the search
ends:
o If
bottom becomes greater than top, display that the element is not found and
stop.
o Find
the middle position.
o If
the middle element is equal to the search element, display the position and
stop.
o If
the middle element is smaller than the search element, search in the right half
by changing bottom to mid + 1.
o If
the middle element is larger than the search element, search in the left half
by changing top to mid - 1.
§
End the process.
def BinarySearch(L,ele):
bottom = 0
top = len(L)-1
while(True):
if (bottom > top):
print("Element not found")
return
mid = (bottom+top)//2
if(L[mid] == ele):
print("Element", ele, "present at position", mid+1)
return
elif (L[mid] < ele):
bottom = mid + 1
else:
top = mid - 1
L = eval(input("Enter list of elements : "))
L.sort()
ele = eval(input("Enter element to search : "))
BinarySearch(L,ele)
No comments:
Post a Comment
Don't be a silent reader...
Leave your comments...
Anu