Searching is the process of finding an element from a group of elements. The group of elements may be an array, list, tuple or dictionary in python.
Binary search is one of the efficient algorithm to find the
element.
Algorithm:
- · First, sort the group elements.
- · let us find the middle index of the group.
- · Check the key with the middle element. If the key value is found, then stop the process and print “key found” message.
- · If the key is not found in the middle element, check the below.
o
If the key is greater than the middle element,
search the element in the right side.
o
Else if the key is less than the middle element,
search the element in the left side.
·
Continue this process until the key is found.
This algorithm can be implemented by two ways in terms of
programming.
# Python code to implement iterative Binary Search.
# To find the location of k in given array bs. where min
refers minimum value. max refers maximum value.
def binarySearch(bs,min, max, k):
while min <=
max:
mid = min +
(max - min) // 2
# Check if k
is present at mid
if bs[mid] ==
k:
return mid
# If k is
greater, ignore left half
elif bs[mid]
< k:
min = mid
+ 1
# If k is
smaller, ignore right half
else:
max = mid
- 1
# The element was
not present
return -1
if __name__ == '__main__':
bs = [24, 35, 42,
50, 60]
k =
int(input(" enter the key value"))
# Function call
output =
binarySearch(bs, 0, len(bs)-1, k)
if output != -1:
print("Element is present at index", output)
else:
print("Element is not present in array")
This is the python program to search an element in an array.
When you execute this code,it shows the following output.
No comments:
Post a Comment